package com.yixun.qfbao.api.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yixun.qfbao.api.service.DeptPermissionService;
import com.yixun.qfbao.api.service.SubscriptionApiService;
import com.yixun.qfbao.api.service.WechatTemplateMessageService;
import com.yixun.qfbao.api.service.WxTemplateMsgService;
import com.yixun.qfbao.apidto.WxMsgCommonDto;
import com.yixun.qfbao.config.H5UrlConfig;
import com.yixun.qfbao.constant.WxMessageTemplate;
import com.yixun.qfbao.dao.DepartmentDao;
import com.yixun.qfbao.model.Company;
import com.yixun.qfbao.model.PartnerInfo;
import com.yixun.qfbao.model.Subscription;
import com.yixun.qfbao.model.WxmsgModel;
import com.yixun.qfbao.model.dto.*;
import com.yixun.qfbao.model.enums.DelFlagEnum;
import com.yixun.qfbao.model.enums.SendStatusEnum;
import com.yixun.qfbao.model.enums.SystemIdEnum;
import com.yixun.qfbao.service.*;
import com.yixun.qfbao.util.DateStyle;
import com.yixun.qfbao.util.DateUtils;
import com.yixun.qfbao.util.StringUtil;
import com.yixun.qfbao.util.TemplateMessageResult;
import com.yixun.qfbao.util.WxAccessTokenCacheUtils;
import com.yixun.qfbao.xf.model.CustomerPremises;
import com.yixun.qfbao.xf.model.Premises;
import com.yixun.qfbao.xf.model.dto.CaseMemberDto;
import com.yixun.qfbao.xf.model.dto.PremisesDto;
import com.yixun.qfbao.xf.model.enums.CustomerStatusEnum;
import com.yixun.qfbao.xf.model.enums.PartnerStatusEnum;
import com.yixun.qfbao.xf.model.enums.ReportWayEnum;
import com.yixun.qfbao.xf.service.CaseMemberService;
import com.yixun.qfbao.xf.service.CustomerPremisesService;
import com.yixun.qfbao.xf.service.PremisesService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class WxTemplateMsgServiceImpl implements WxTemplateMsgService {

    private static final Logger logger = LoggerFactory.getLogger(WxTemplateMsgServiceImpl.class);

    private static final String AGENCY_SYSTEM = "agency";
    private static final String ASSISTANT_SYSTEM = "assistant";
    private static final String COMPANY_UUID = "COMPANYUUID";
    private static final String CUS_PRE_ID = "CUSPREID";

    @Autowired
    private H5UrlConfig h5UrlConfig;
    // 案场助手报备详情地址
    private String assistantCusPreDetailUrl = "?companyUUid=COMPANYUUID#/customerDetails/CUSPREID/templateMessage";
    // 分销助手报备详情地址
    private String agencyCusPreDetailUrl = "?companyUUid=COMPANYUUID#/declareDetail/CUSPREID/templateMessage";

    @Autowired
    private PartnerInfoService partnerInfoService;
    @Autowired
    private CaseMemberService caseMemberService;
    @Autowired
    private PremisesService premisesService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private SubscriptionApiService subscriptionApiService;
    @Autowired
    private WechatTemplateMessageService wechatTemplateMessageService;
    @Autowired
    private DepartmentDao departmentDao;
    @Autowired
    private WxmsgModelService wxmsgModelService;
    @Autowired
    private WxmsgFailureService wxmsgFailureService;
    @Autowired
    private CustomerPremisesService customerPremisesService;
    @Autowired
    private WxAccessTokenCacheUtils wxAccessTokenCacheUtils;
    @Lazy
    @Autowired
    private DeptPermissionService deptPermissionService;
    /**
     * 发送到访成功模板消息
     * 不会发给案场，无需关注隐号
     * @param agencyAccessToken
     * @param cusPre
     * @param wxMsgCommonDto
     * @param visitTime
     */
    @Override
    @Async
    public void sendVisitSuccessTemplateMsg(String agencyAccessToken, CustomerPremises cusPre, WxMsgCommonDto wxMsgCommonDto, Date visitTime) {
        //发送微信模板消息
        if (StringUtils.isBlank(agencyAccessToken)) {
            return;
        }
        //获取经纪人openId
        PartnerInfoDto partnerInfoDto = new PartnerInfoDto();
        partnerInfoDto.setId(cusPre.getStaffId());
        partnerInfoDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
        partnerInfoDto.setStatus(PartnerStatusEnum.VALID.getNo());
        
        PartnerInfo agentPi = partnerInfoService.selectByDto(partnerInfoDto);
        //组装报备经纪人
        List<String> openIdList = new ArrayList<>();
        openIdList.add(agentPi != null ? agentPi.getWxOpenid():"");
        
        List<PartnerInfo> reveivePartnerInfos = new ArrayList<>();
        reveivePartnerInfos.add(agentPi);

        Premises premises = premisesService.selectSimpleById(cusPre.getPremisesId());
        String premisesName = premises!=null&&StringUtils.isNotBlank(premises.getName()) ? premises.getName() : "";

        Company company = companyService.selectById(premises.getCompanyId());
        
        // add by zilong.liu  添加获取真实token的方法
        String modelSystemId = SystemIdEnum.AGENCY_h5.getCode();
        if (agentPi != null) {
        	agencyAccessToken = wxAccessTokenCacheUtils.getAccessTokenIfWeappMsg(company, agentPi.getLastLoginSystemId(), agencyAccessToken);
        	// 原固定使用分销助手的模板，现如果登录是分校小程序，需要使用小程序对应公众号配置的对应模板,需要添加是否开启开关的判断
        	modelSystemId = (SystemIdEnum.WEAPP_AGENCY.getCode().equals(agentPi.getLastLoginSystemId()) 
        			&& "1".equals(company.getEnableWeappMsg()))? 
        					SystemIdEnum.WEAPP_AGENCY_WX_ACCOUNTS.getCode(): SystemIdEnum.AGENCY_h5.getCode();
        }
        // add by zilong.liu  添加获取真实token的方法

        // 根据域名或者公司uuid查询开发商
        Map<Integer,WxmsgModel> mpwx = subscriptionApiService.getSubscriptionModelMsg(company.getCompanyUuid(),wxMsgCommonDto.getDomain(), modelSystemId);
        if(mpwx == null || mpwx.size() == 0) {
        	logger.info("agencyWxMap is null, 请检查运营后台配置。companyUuid:{}", company.getCompanyUuid());
        	return;
        }
        // 判断权限
//        boolean flag = wxmsgModelService.checkWeixinModelSet(company.getId(),company.getCompanyUuid(),wxMsgCommonDto.getDomain(),WxMessageTemplate.VISIT_SUCCESS_TEMPLATE_ID);
//        if(!flag){
//            logger.info("sendVisitSuccessTemplateMsg ---- 未打开,公司: {}, 模板: {}", company.getCompanyUuid(), WxMessageTemplate.VISIT_SUCCESS_TEMPLATE_ID);
//            return;
//        }
        for (String openId : openIdList) {
            try {
                TreeMap<String,HashMap<String,String>> params = new TreeMap<>();
                params.put("first", WechatTemplateMsg.item("到访确认成功！"));
                params.put("keyword1",WechatTemplateMsg.item(cusPre.getName()+" "+cusPre.getMobile()));
                params.put("keyword2",WechatTemplateMsg.item(premisesName));
                params.put("keyword3",WechatTemplateMsg.item("到访确认成功"));
                params.put("keyword4",WechatTemplateMsg.item(company!=null?company.getCompanyName():""));
                // 预计到访时间 V10可以传值为空
                if(visitTime != null){
                    params.put("remark",WechatTemplateMsg.item("到访时间："+ DateUtils.DateToString(visitTime, DateStyle.YYYY_MM_DD_HH_MM_SS)+"，请及时跟进后续业务"));
                }else{
                    params.put("remark", WechatTemplateMsg.item("\n请及时跟进后续业务！"));
                }

                WechatTemplateMsg wechatTemplateMsg = new WechatTemplateMsg();
                wechatTemplateMsg.setTemplate_id(mpwx.get(WxMessageTemplate.VISIT_SUCCESS_TEMPLATE_ID).getWxModelmsgId());
                wechatTemplateMsg.setTouser(openId);
                wechatTemplateMsg.setData(params);
                String url = h5UrlConfig.getWxTemplateMsgAgencyUrl() + agencyCusPreDetailUrl.replace(COMPANY_UUID, company.getCompanyUuid()).replace(CUS_PRE_ID, cusPre.getId().toString());
                wechatTemplateMsg.setUrl(url);
                
                //add by liuzilong 消息下发时，最后一次登录是小程序的话打开链接可跳转至小程序
                if(agentPi != null && company != null) {
                	addMiniProgram(agentPi.getLastLoginSystemId(), company.getCompanyUuid(), company.getEnableWeappMsg(), wechatTemplateMsg, cusPre.getId());
                }
                //add by liuzilong 消息下发时，最后一次登录是小程序的话打开链接可跳转至小程序
                
                String data = JSON.toJSONString(wechatTemplateMsg);
                TemplateMessageResult result = wechatTemplateMessageService.sendTemplate(agencyAccessToken, data);
                String companyUuid = company.getCompanyUuid();
//                String systemId = SystemIdEnum.AGENCY_h5.getCode();
                String receiveOpenId = openId;
                String modelType = String.valueOf(WxMessageTemplate.VISIT_SUCCESS_TEMPLATE_ID);
                String modelUuid = mpwx.get(WxMessageTemplate.VISIT_SUCCESS_TEMPLATE_ID).getWxModelmsgId();
                
                buildWXFailureMsg(getPartnerId(reveivePartnerInfos, receiveOpenId), companyUuid, modelSystemId, receiveOpenId, data, modelType, modelUuid, result, cusPre.getId());
                Thread.sleep(1000L);
            } catch (InterruptedException ie) {
                logger.error("sendVisitSuccessTemplateMsg InterruptedException---- 发送微信模板消息失败：{}", ie);
            } catch (Exception e) {
                logger.error("sendVisitSuccessTemplateMsg ---- 发送微信模板消息失败：{}", e);
            }
        }
    }
    
    /**
     * 	判断是否有相同的wxOpenId，有则返回当前的Id。这样会有点小问题。。。如果存在wxOpenId一致的时候。但是99%的情况应该是没问题的。
     * 	 避免该出更多的bug，简化开发，先这样处理 。 极少数情况出现的问题应该不会对实际造成比较大的影响。
     * @param partnerInfoList
     * @param wxOpenId
     * @return
     */
    private Long getPartnerId(List<PartnerInfo> partnerInfoList, String wxOpenId) {
    	Long partnerId = 0L;
    	if(!StringUtil.isNotNull(wxOpenId)) {
    		return partnerId;
    	}
    	if(CollectionUtils.isEmpty(partnerInfoList)) {
    		return partnerId;
    	}
    	for (PartnerInfo partnerInfo : partnerInfoList) {
			if(Objects.nonNull(partnerInfo) && wxOpenId.equals(partnerInfo.getWxOpenid())) {
				partnerId = partnerInfo.getId();
				break;
			}
		}
    	return partnerId;
    }
    
    /**
     * 小程序页面路径
     */
    private static final String[] MINIPROGRAM_PATH_ARRAY = {"pages/index/index", "pages/login/register",
    		"pages/login/auditResult", "pages/login/register"};
    
    /**
     * 在下发的微信模板消息中添加小程序跳转链接
     * @param lastLoginSystemId
     * @param companyUuid
     * @param wechatTemplateMsg, 需要从wechatTemplateMsg
     */
    private void addMiniProgram(String lastLoginSystemId, String companyUuid, String enableWeappMsg,
    		WechatTemplateMsg wechatTemplateMsg, long id) {
    	if(!SystemIdEnum.WEAPP_AGENCY.getCode().equals(lastLoginSystemId) || !"1".equals(enableWeappMsg)) {
    		return;
    	}
    	// 获取appId
    	Subscription Subscription = subscriptionApiService.getSubscriptionInfo(companyUuid, "", lastLoginSystemId);
    	Miniprogram miniProgram = new Miniprogram();
    	miniProgram.setAppid(Subscription.getAppId());
    	// 后期可能根据URL判断跳转至不同的界面
    	String url = wechatTemplateMsg.getUrl();
    	for(int i = 0; i < MINIPROGRAM_PATH_ARRAY.length; i ++) {
    		if(MINIPROGRAM_PATH_ARRAY[i].equals(url)) {
    			miniProgram.setPagepath(id == 0L ? url: (url + "?id=" +  id));
    			wechatTemplateMsg.setMiniprogram(miniProgram);
    	    	wechatTemplateMsg.setUrl(null);
    	    	return;
    		}
    	}
//    	String pagePath = "";
//    	if(url.indexOf("declareDetail") > 0) {
//    	}
    	String pagePath = convertCusPrePageUrl(id);
    	miniProgram.setPagepath(pagePath);
    	wechatTemplateMsg.setMiniprogram(miniProgram);
    	wechatTemplateMsg.setUrl(null);
    }
    
    /**
     * 转换公众号URL至小程序链接
     * @return
     */
    private String convertCusPrePageUrl(long cusPreId) {
    	// 如果是报备，则跳转到对应的报备页面
    	return "pages/report/reportDetail?reportId=" + cusPreId;
    }

    /**
     * 发送签约成功模板消息
     * 需要发送给案场，已处理
     * @param agencyAccessToken
     * @param assistantAccessToken
     * @param cusPre
     * @param devCompanyName
     * @param reqDto
     */
    @Override
    @Async
    public void sendSignSuccessTemplateMsg(String agencyAccessToken, String assistantAccessToken, CustomerPremises cusPre, String devCompanyName, WxMsgCommonDto reqDto) {
        //发送微信模板消息
        if (StringUtils.isBlank(agencyAccessToken) && StringUtils.isBlank(assistantAccessToken)) {
            logger.info("sendSignSuccessTemplateMsg ---- agencyAccessToken和assistantAccessToken为空，不发送模板消息");
            return;
        }

        // 判断权限
//        boolean flag = wxmsgModelService.checkWeixinModelSet(null,reqDto.getCompanyUuid(),reqDto.getDomain(),WxMessageTemplate.SIGN_TEMPLATE_ID);
//        if(!flag){
//            logger.info("sendSignSuccessTemplateMsg ---- 发送微信模板消息失败：发送签约成功模板消息开关未打开");
//            return;
//        }

        //获取经纪人openId
        PartnerInfoDto partnerInfoDto = new PartnerInfoDto();
        partnerInfoDto.setId(cusPre.getStaffId());
        partnerInfoDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
        partnerInfoDto.setStatus(PartnerStatusEnum.VALID.getNo());
        PartnerInfo agentPi = partnerInfoService.selectByDto(partnerInfoDto);

        CaseMemberDto caseMemberDto = new CaseMemberDto();
        caseMemberDto.setPremisesId(cusPre.getPremisesId());
        List<PartnerInfo> partnerInfoList = caseMemberService.selectListForWxMsg(caseMemberDto);
        // 筛选出有权限的用户
        partnerInfoList = filterPartnerByPermission(partnerInfoList, agentPi);
        List<String> assignOpenIdList = null;
        if(partnerInfoList != null && partnerInfoList.size() > 0) {
            assignOpenIdList = partnerInfoList.stream().filter(partnerInfo -> partnerInfo.getWxOpenid() != null).map(PartnerInfo::getWxOpenid).collect(Collectors.toList());
        }

        List<String> hideWxOpenIds = getHideWxOpenIds(assignOpenIdList);

        //组装报备经纪人
        Map<String, List<String>> openIdMap = new HashMap<>();
        List<String> openIdList = new ArrayList<>();
        //经纪人（分销助手）
        openIdList.add(agentPi != null ? agentPi.getWxOpenid():"");
        openIdMap.put(AGENCY_SYSTEM, openIdList);
        //案场人员（渠道助手）
        openIdMap.put(ASSISTANT_SYSTEM, assignOpenIdList);
        List<PartnerInfo> reveivePartnerInfos = new ArrayList<>();
        reveivePartnerInfos.add(agentPi);
        if(CollectionUtils.isNotEmpty(partnerInfoList)) {
            reveivePartnerInfos.addAll(partnerInfoList);
        }

        Premises premises = premisesService.selectSimpleById(cusPre.getPremisesId());
        String premisesName = premises!=null&&StringUtils.isNotBlank(premises.getName()) ? premises.getName() : "";
        String companyUuid = reqDto.getCompanyUuid();
        // update by zilong.liu  , 获取真实的token，目前只更改分销的信息
        Company company = companyService.selectById(premises.getCompanyId());
        if(StringUtils.isBlank(companyUuid)){
            logger.info("sendSignSuccessTemplateMsg ---> companyuuid is null");
            companyUuid = company.getCompanyUuid();
        }
        String modelSystemId = SystemIdEnum.AGENCY_h5.getCode();
        if (agentPi != null) {
        	agencyAccessToken = wxAccessTokenCacheUtils.getAccessTokenIfWeappMsg(company, agentPi.getLastLoginSystemId(), agencyAccessToken);
        	modelSystemId = (SystemIdEnum.WEAPP_AGENCY.getCode().equals(agentPi.getLastLoginSystemId()) 
        			&& "1".equals(company.getEnableWeappMsg()))?  
        					SystemIdEnum.WEAPP_AGENCY_WX_ACCOUNTS.getCode(): SystemIdEnum.AGENCY_h5.getCode();
        }
		// 根据域名或者公司uuid查询开发商, 
		Map<Integer,WxmsgModel> agencyWxMap = subscriptionApiService.getSubscriptionModelMsg(companyUuid,reqDto.getDomain(), modelSystemId);
        if(agencyWxMap == null || agencyWxMap.size() == 0) {
        	logger.info("agencyWxMap is null, 请检查运营后台配置, companyUuid:{}", companyUuid);
        	return;
        }
		// update by zilong.liu   , 获取真实的token，目前只更改分销的信息
        

        Map<Integer,WxmsgModel> assistantWxMap = subscriptionApiService.getSubscriptionModelMsg(companyUuid,reqDto.getDomain(),SystemIdEnum.ASSISTANT.getCode());
        if(assistantWxMap == null || assistantWxMap.size() == 0 || assistantWxMap.get(WxMessageTemplate.SIGN_TEMPLATE_ID) == null) {
        	openIdMap.remove(ASSISTANT_SYSTEM);
        }
        
        for (String systemType : openIdMap.keySet()) {
            //agencyAccessToken或assistantAccessToken 为空说明获取失败或者未开通发送模板消息
            if((systemType.equals(AGENCY_SYSTEM) && StringUtils.isBlank(agencyAccessToken))
                    || (systemType.equals(ASSISTANT_SYSTEM) && StringUtils.isBlank(assistantAccessToken))) {
                continue;
            }
            List<String> openIdTempList = openIdMap.get(systemType);
            if(CollectionUtils.isEmpty(openIdTempList)){
                return;
            }
            for (String openId : openIdTempList) {
                try {
                    TreeMap<String,HashMap<String,String>> params = new TreeMap<>();
                    params.put("first",WechatTemplateMsg.item("恭喜签约成功！"));
                    String realPhone = getRealPhoneByCaseMemberAuth(hideWxOpenIds, cusPre.getMobile(), openId, systemType, cusPre.getPremisesId());
                    params.put("keyword1",
                    		WechatTemplateMsg.item(cusPre.getName()+" "+realPhone));
                    params.put("keyword2",WechatTemplateMsg.item(premisesName));
                    params.put("keyword3",WechatTemplateMsg.item("签约成功"));
                    params.put("keyword4",WechatTemplateMsg.item(devCompanyName));
                    params.put("remark",WechatTemplateMsg.item("请及时跟进后续业务"));
                    WechatTemplateMsg wechatTemplateMsg = new WechatTemplateMsg();
                    String templateId = null;
                    String url = null;
                    if (systemType.equals(AGENCY_SYSTEM) && !agencyWxMap.isEmpty()) {
                        templateId = agencyWxMap.get(WxMessageTemplate.SIGN_TEMPLATE_ID).getWxModelmsgId();
                        url = h5UrlConfig.getWxTemplateMsgAgencyUrl() + agencyCusPreDetailUrl;
                        url = url.replace(COMPANY_UUID, companyUuid).replace(CUS_PRE_ID, cusPre.getId().toString());
                        wechatTemplateMsg.setUrl(url);
                        //add by zilong.liu 最后登录分销小程序跳转至小程序
                        if(agentPi != null && company != null) {
                        	addMiniProgram(agentPi.getLastLoginSystemId(), companyUuid, company.getEnableWeappMsg(), wechatTemplateMsg, cusPre.getId());
                        }
                        //add by zilong.liu 最后登录分销小程序跳转至小程序
                    } else {
                        templateId = assistantWxMap.get(WxMessageTemplate.SIGN_TEMPLATE_ID).getWxModelmsgId();
                        url = h5UrlConfig.getWxTemplateMsgAssistantUrl() + assistantCusPreDetailUrl;
                        url = url.replace(COMPANY_UUID, companyUuid).replace(CUS_PRE_ID, cusPre.getId().toString());
                        wechatTemplateMsg.setUrl(url);
                    }
                    wechatTemplateMsg.setTemplate_id(templateId);
                    wechatTemplateMsg.setTouser(openId);
                    wechatTemplateMsg.setData(params);
                    
                    String data = JSON.toJSONString(wechatTemplateMsg);
                    TemplateMessageResult result = wechatTemplateMessageService.sendTemplate(systemType.equals(AGENCY_SYSTEM)?agencyAccessToken:assistantAccessToken, data);

                    // update by zilong.liu  分销小程序渠道变更
                    String systemId = modelSystemId;
                    if(systemType.equals(ASSISTANT_SYSTEM)) {
                    	systemId = SystemIdEnum.ASSISTANT.getCode();
                    }
//                    String systemId = systemType.equals(AGENCY_SYSTEM)?SystemIdEnum.AGENCY_h5.getCode(): SystemIdEnum.ASSISTANT.getCode();
                    // update by zilong.liu  分销小程序渠道变更
                    String receiveOpenId = openId;
                    String modelType = String.valueOf(WxMessageTemplate.SIGN_TEMPLATE_ID);
                    String modelUuid = templateId;
                    buildWXFailureMsg(getPartnerId(reveivePartnerInfos, receiveOpenId), companyUuid, systemId, receiveOpenId, data, modelType, modelUuid, result, cusPre.getId());

                    Thread.sleep(1000L);
                } catch (InterruptedException ie) {
                    logger.error("sendSignSuccessTemplateMsg InterruptedException---- 发送微信模板消息失败：{}", ie);
                } catch (Exception e) {
                    logger.error("sendSignSuccessTemplateMsg ---- 发送微信模板消息失败：{}", e);
                }
            }
        }
    }

    /**
     * 发送报备成功模板消息
     * 需要发送给案场，已处理
     * @param agencyAccessToken
     * @param assistantAccessToken
     * @param customerPremises
     * @param wxMsgCommonDto
     */
    @Override
    @Async
    public void sendReportSuccessTemplateMsg(String agencyAccessToken, String assistantAccessToken, CustomerPremises customerPremises, WxMsgCommonDto wxMsgCommonDto) {
        if(StringUtils.isBlank(agencyAccessToken) && StringUtils.isBlank(assistantAccessToken)) {
            return;
        }
        // 判断权限
//        boolean flag = wxmsgModelService.checkWeixinModelSet(null,wxMsgCommonDto.getCompanyUuid(),wxMsgCommonDto.getDomain(),WxMessageTemplate.REPORT_SUCCESS_TEMPLATE_ID);
//        if(!flag){
//            logger.info("sendReportSuccessTemplateMsg ---- 发送微信模板消息失败：发送报备成功开关未打开");
//            return;
//        }

        //获取经纪人openId
        PartnerInfo agentPi = partnerInfoService.selectById(customerPremises.getStaffId());
        if(agentPi == null) {
            logger.info("sendReportSuccessTemplateMsg ---- 获取经纪人信息失败！");
        }

        //发送微信模板消息
        CaseMemberDto caseMemberDto = new CaseMemberDto();
        caseMemberDto.setPremisesId(customerPremises.getPremisesId());
        List<PartnerInfo> partnerInfoList = caseMemberService.selectListForWxMsg(caseMemberDto);
        // 筛选出有权限的用户
        partnerInfoList = filterPartnerByPermission(partnerInfoList, agentPi);
        List<String> assignOpenIdList = null;
        if(partnerInfoList != null && partnerInfoList.size() > 0) {
            assignOpenIdList = partnerInfoList.stream().filter(partnerInfo -> partnerInfo.getWxOpenid() != null).map(PartnerInfo::getWxOpenid).collect(Collectors.toList());
        }

        // 获取分销公司组织信息
        Organization organization = companyService.getOrganizationInfo(agentPi.getHigherid(), agentPi.getDeptId());

        DepartmentDto departDto = departmentDao.getPrincipal(customerPremises.getStaffId());
        String principalName ="";
        if(departDto!=null){
            principalName = StringUtils.isEmpty(departDto.getPrincipalName())?"":departDto.getPrincipalName();
        }
        //组装报备经纪人
        Map<String,List<String>> openIdMap = new HashMap<>();
        List<String> openIdList = new ArrayList<>();
        boolean agentPiFlag = agentPi != null && DelFlagEnum.UNDEL.getNo().equals(agentPi.getDelFlag())
                && PartnerStatusEnum.VALID.getNo().equals(agentPi.getStatus());
        openIdList.add(agentPiFlag ? agentPi.getWxOpenid() : "");

        List<PartnerInfo> reveivePartnerInfos = new ArrayList<>();
        reveivePartnerInfos.add(agentPi);
        if(CollectionUtils.isNotEmpty(partnerInfoList)){
            reveivePartnerInfos.addAll(partnerInfoList);
        }

        //代报备人
        if(null != customerPremises && null != customerPremises.getPartnerId()){
            String replaceOpenId = partnerInfoService.getReplaceReporterOpenId(reveivePartnerInfos, customerPremises.getPartnerId());
            if(replaceOpenId != null) {
                assignOpenIdList.add(replaceOpenId);
            }
        }
        List<String> hideWxOpenIds = getHideWxOpenIds(assignOpenIdList);
        List<String> hideAgentPhoneOpenIds = getHideAgentPhoneOpenIds(assignOpenIdList);

        openIdMap.put(AGENCY_SYSTEM, openIdList);
        openIdMap.put(ASSISTANT_SYSTEM, assignOpenIdList);

        Premises premises = premisesService.selectSimpleById(customerPremises.getPremisesId());
        String premisesName = premises != null && StringUtils.isNotBlank(premises.getName()) ? premises.getName() : "";
        String companyUuid = wxMsgCommonDto.getCompanyUuid();
        // update by zilong.liu update for分销小程序消息
        Company company = companyService.selectById(premises.getCompanyId());
        if(StringUtils.isBlank(companyUuid)){
            logger.info("sendReportSuccessTemplateMsg ---> companyuuid is null");
            companyUuid = company.getCompanyUuid();
        }
        String modelSystemId = SystemIdEnum.AGENCY_h5.getCode();
        if (agentPi != null) {
        	agencyAccessToken = wxAccessTokenCacheUtils.getAccessTokenIfWeappMsg(company, agentPi.getLastLoginSystemId(), agencyAccessToken);
        	modelSystemId = (SystemIdEnum.WEAPP_AGENCY.getCode().equals(agentPi.getLastLoginSystemId()) 
        			&& "1".equals(company.getEnableWeappMsg()))?  
        					SystemIdEnum.WEAPP_AGENCY_WX_ACCOUNTS.getCode(): SystemIdEnum.AGENCY_h5.getCode();
        }
        logger.info("sendReportSuccessTemplateMsg ---> companyuuid:{}", companyUuid);
        logger.info("sendReportSuccessTemplateMsg ---> modelSystemId:{}", modelSystemId);
		Map<Integer,WxmsgModel> agencyWxMap = subscriptionApiService.getSubscriptionModelMsg(companyUuid,wxMsgCommonDto.getDomain(),modelSystemId);
		if(agencyWxMap == null || agencyWxMap.size() == 0) {
        	logger.info("agencyWxMap is null, 请检查运营后台配置。companyUuid{}", companyUuid);
        	return;
        }
		logger.info("sendReportSuccessTemplateMsg ---> agencyWxMap", String.valueOf(agencyWxMap));
		logger.info("sendReportSuccessTemplateMsg ---> agencyWxMap:{}", String.valueOf(agencyWxMap));
		// update by zilong.liu update for分销小程序消息
        // 根据域名或者公司uuid查询开发商
        Map<Integer,WxmsgModel> assistantWxMap = subscriptionApiService.getSubscriptionModelMsg(companyUuid,wxMsgCommonDto.getDomain(),SystemIdEnum.ASSISTANT.getCode());
        if(assistantWxMap == null || assistantWxMap.size() == 0 || assistantWxMap.get(WxMessageTemplate.REPORT_SUCCESS_TEMPLATE_ID) == null) {
        	openIdMap.remove(ASSISTANT_SYSTEM);
        }
        
        for (String systemType : openIdMap.keySet()) {
            //agencyAccessToken或assistantAccessToken 为空说明获取失败或者未开通发送模板消息
            if ((systemType.equals(AGENCY_SYSTEM) && StringUtils.isBlank(agencyAccessToken))
                    || (systemType.equals(ASSISTANT_SYSTEM) && StringUtils.isBlank(assistantAccessToken))) {
                continue;
            }
            List<String> openIdTempList = openIdMap.get(systemType);
            if(CollectionUtils.isEmpty(openIdTempList)){
                return;
            }
            for (String openId : openIdTempList) {
                try {
                    TreeMap<String, HashMap<String, String>> params = new TreeMap<>();
                    params.put("first", WechatTemplateMsg.item("报备确认成功，可带看客户"));
                    params.put("keyword1", WechatTemplateMsg.item(premisesName + " 对接人:" + principalName));
                    String realPhone = getRealPhoneByCaseMemberAuth(hideWxOpenIds, customerPremises.getMobile(), openId, systemType, customerPremises.getPremisesId());
                    params.put("keyword2", WechatTemplateMsg.item(customerPremises.getName() + " " + realPhone));
                    params.put("keyword3", WechatTemplateMsg.item(DateUtils.DateToString(customerPremises.getCreateTime(), DateStyle.YYYY_MM_DD_HH_MM_SS)));
                    String agentPhone = getAgentPhoneByCaseMemberAuth(hideAgentPhoneOpenIds, agentPi.getPhone(), openId, systemType, customerPremises.getPremisesId());
                    params.put("keyword4", WechatTemplateMsg.item(
                            organization.getCompanyName() + " - "
                            + organization.getDepartmentName() + " "
                            //+ organization.getGroupName() + " "
                            //+ organization.getStoreName() + " "
                            + agentPi.getAccountName() + " "
                            + agentPhone));
                    // 预计到访时间 V10可以传值为空
                    if(customerPremises.getHopeVisitTime() != null){
                        String visitTime = DateUtils.DateToString(customerPremises.getHopeVisitTime(), DateStyle.YYYY_MM_DD_HH_MM_SS);
                        visitTime = StringUtils.isBlank(visitTime) ? "" : visitTime;
                        params.put("remark", WechatTemplateMsg.item("到访时间：" + visitTime));
                    }
                    WechatTemplateMsg wechatTemplateMsg = new WechatTemplateMsg();
                    String templateId = null;
                    String url = null;
                    if (systemType.equals(AGENCY_SYSTEM) && !agencyWxMap.isEmpty()) {
                        templateId = agencyWxMap.get(WxMessageTemplate.REPORT_SUCCESS_TEMPLATE_ID).getWxModelmsgId();
                        url = h5UrlConfig.getWxTemplateMsgAgencyUrl() + agencyCusPreDetailUrl;
                        url = url.replace(COMPANY_UUID, companyUuid).replace(CUS_PRE_ID, customerPremises.getId().toString());
                        wechatTemplateMsg.setUrl(url);
                        //add by zilong.liu 最后登录分销小程序跳转至小程序
                        if(agentPi != null && company != null) {
                        	addMiniProgram(agentPi.getLastLoginSystemId(), companyUuid, company.getEnableWeappMsg(), wechatTemplateMsg, customerPremises.getId());
                        }
                        //add by zilong.liu 最后登录分销小程序跳转至小程序
                    } else {
                        templateId = assistantWxMap.get(WxMessageTemplate.REPORT_SUCCESS_TEMPLATE_ID).getWxModelmsgId();
                        url = h5UrlConfig.getWxTemplateMsgAssistantUrl() + assistantCusPreDetailUrl;
                        url = url.replace(COMPANY_UUID, companyUuid).replace(CUS_PRE_ID, customerPremises.getId().toString());
                        wechatTemplateMsg.setUrl(url);
                    }
                    
                    wechatTemplateMsg.setTemplate_id(templateId);
                    wechatTemplateMsg.setTouser(openId);
                    wechatTemplateMsg.setData(params);
//                    wechatTemplateMsg.setUrl(url);
                    String data = JSON.toJSONString(wechatTemplateMsg);
                    TemplateMessageResult result =  wechatTemplateMessageService.sendTemplate(systemType.equals(AGENCY_SYSTEM)?agencyAccessToken:assistantAccessToken, data);

                    // update by zilong.liu  分销小程序渠道变更
                    String systemId = modelSystemId;
                    if(systemType.equals(ASSISTANT_SYSTEM)) {
                    	systemId = SystemIdEnum.ASSISTANT.getCode();
                    }
//                  String systemId = systemType.equals(AGENCY_SYSTEM)?SystemIdEnum.AGENCY_h5.getCode(): SystemIdEnum.ASSISTANT.getCode();
                    // update by zilong.liu  分销小程序渠道变更
                    String receiveOpenId = openId;
                    String modelType = String.valueOf(WxMessageTemplate.REPORT_SUCCESS_TEMPLATE_ID);
                    String modelUuid = templateId;
                    buildWXFailureMsg(getPartnerId(reveivePartnerInfos, receiveOpenId), companyUuid, systemId, receiveOpenId, data, modelType, modelUuid, result, customerPremises.getId());

                    Thread.sleep(1000L);
                } catch (InterruptedException ie) {
                    logger.error("sendReportSuccessTemplateMsg InterruptedException---- 发送微信模板消息失败：{}", ie);
                } catch (Exception e) {
                    logger.error("sendReportSuccessTemplateMsg ---- 发送微信模板消息失败：{}", e);
                }
            }
        }
    }
    /**
     * 发送报备成功模板消息
     * 需要发送给案场，已处理
     * @param agencyAccessToken
     * @param assistantAccessToken
     * @param customerPremises
     * @param companyUuid
     */
    @Override
    @Async
    public void sendReportSuccessTemplateMsgForV10(String agencyAccessToken, String assistantAccessToken, CustomerPremises customerPremises, String companyUuid) {
        if (StringUtils.isBlank(assistantAccessToken)) {
            logger.info("sendReportSuccessTemplateMsgForV10 ---- assistantAccessToken为空，不发送模板消息");
            return;
        }
        if(null == customerPremises.getPremisesId()) {
            logger.info("sendReportSuccessTemplateMsgForV10 ---- 楼盘ID不能为空！");
            return;
        }
        if(StringUtils.isBlank(companyUuid)) {
            logger.info("sendReportSuccessTemplateMsgForV10 ---- companyUuid和domain不能同时为空！");
            return;
        }
        if(null == customerPremises.getStaffId()) {
            logger.info("sendReportSuccessTemplateMsgForV10 ---- 经纪人ID不能为空！");
            return;
        }
        // 判断权限
//        boolean flag = wxmsgModelService.checkWeixinModelSet(null,companyUuid, null, WxMessageTemplate.REPORT_CHECK_TEMPLATE_ID);
//        if(!flag){
//            logger.info("sendReportSuccessTemplateMsgForV10 ---- 发送微信模板消息失败：发送报备审核模板开关未打开");
//            return;
//        }

        //获取经纪人信息
        PartnerInfo agentPi = partnerInfoService.selectById(Long.valueOf(customerPremises.getStaffId()));
        if(agentPi == null) {
            logger.info("sendReportSuccessTemplateMsgForV10 ---- 获取经纪人信息失败！");
            return;
        }

        //获取接收微信模板消息驻场人员openid
        CaseMemberDto caseMemberDto = new CaseMemberDto();
        caseMemberDto.setPremisesId(customerPremises.getPremisesId());
        List<PartnerInfo> partnerInfoList = caseMemberService.selectListForWxMsg(caseMemberDto);
        // 筛选出有权限的用户
        partnerInfoList = filterPartnerByPermission(partnerInfoList, agentPi);
        List<String> assignOpenIdList = null;
        if(partnerInfoList != null && partnerInfoList.size() > 0) {
            assignOpenIdList = partnerInfoList.stream().filter(partnerInfo -> partnerInfo.getWxOpenid() != null).map(PartnerInfo::getWxOpenid).collect(Collectors.toList());
        }
        if (assignOpenIdList == null) {
            logger.info("sendReportSuccessTemplateMsgForV10 ---- 获取驻场人员openId失败或者数据为空！");
            return;
        }
        List<PartnerInfo> reveivePartnerInfos = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(partnerInfoList)) {
            reveivePartnerInfos.addAll(partnerInfoList);
        }
        List<String> hideWxOpenIds = getHideWxOpenIds(assignOpenIdList);
        List<String> hideAgentPhoneOpenIds = getHideAgentPhoneOpenIds(assignOpenIdList);
        //楼盘信息
        PremisesDto premisesDto = new PremisesDto();
        premisesDto.setId(customerPremises.getPremisesId());
        List<Premises> premisesList = premisesService.selectIdListByDto(premisesDto);
        if(premisesList == null || premisesList.size() == 0) {
            logger.info("sendReportSuccessTemplateMsgForV10 ---- 未获取到楼盘信息！");
            return;
        }
        Premises premises = premisesList.get(0);
        Company company = companyService.selectById(premises.getCompanyId());
        if(null == company) {
            logger.info("sendReportSuccessTemplateMsgForV10 ---- 未获取到商户信息！");
            return;
        }
        companyUuid = company.getCompanyUuid();
        //获取对接人
        DepartmentDto departDto = departmentDao.getPrincipalForWxMsg(customerPremises.getStaffId());
        String principalName = departDto != null ? departDto.getPrincipalName() : "";

        //经纪人公司名称
        Organization organization = companyService.getOrganizationInfo(agentPi.getHigherid(), agentPi.getDeptId());
        //获取微信模板配置失败
        Map<Integer,WxmsgModel> assistantWxMap = subscriptionApiService.getSubscriptionModelMsg(companyUuid
                , null, SystemIdEnum.ASSISTANT.getCode());
        if (assistantWxMap == null || assistantWxMap.size() == 0 || assistantWxMap.get(WxMessageTemplate.REPORT_CHECK_TEMPLATE_ID) == null) {
            logger.info("sendReportSuccessTemplateMsgForV10 ---- 获取微信模板配置失败！");
            return;
        }
        //报备时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String reportTime = sdf.format(customerPremises.getCreateTime());

        for (String openId : assignOpenIdList) {
            logger.info("openId =========" + openId);
            logger.info("assistantAccessToken =========" + assistantAccessToken);
            try {
                TreeMap<String, HashMap<String, String>> params = new TreeMap<>();
                params.put("first", WechatTemplateMsg.item("有一条新的报备通知，请查看"));
                params.put("keyword1", WechatTemplateMsg.item(premises.getName() + " 对接人" + principalName));
                String realPhone = getRealPhoneByCaseMemberAuth(hideWxOpenIds, customerPremises.getMobile(), openId, ASSISTANT_SYSTEM, customerPremises.getPremisesId());
                params.put("keyword2", WechatTemplateMsg.item(customerPremises.getName() + " " + realPhone));
                params.put("keyword3", WechatTemplateMsg.item(reportTime));
                String agentPhone = getAgentPhoneByCaseMemberAuth(hideAgentPhoneOpenIds, agentPi.getPhone(), openId, ASSISTANT_SYSTEM, customerPremises.getPremisesId());
                params.put("keyword4", WechatTemplateMsg.item(
                        organization.getCompanyName() + " - "
                        + organization.getDepartmentName() + " "
                        //+ organization.getGroupName() + " "
                        //+ organization.getStoreName() + " "
                        + agentPi.getAccountName() + " "
                        + agentPhone));
                // 预计到访时间 V10可以传值为空
                if(customerPremises.getHopeVisitTime() != null){
                    params.put("remark", WechatTemplateMsg.item("到访时间：" + DateUtils.DateToString(customerPremises.getHopeVisitTime(), DateStyle.YYYY_MM_DD_HH_MM_SS) + "\n烦请审批通过，感谢！"));
                }else{
                    params.put("remark", WechatTemplateMsg.item("\n烦请审批通过，感谢！"));
                }
                WechatTemplateMsg wechatTemplateMsg = new WechatTemplateMsg();
                wechatTemplateMsg.setTemplate_id(assistantWxMap.get(WxMessageTemplate.REPORT_CHECK_TEMPLATE_ID).getWxModelmsgId());
                wechatTemplateMsg.setTouser(openId);
                wechatTemplateMsg.setData(params);
                String url = h5UrlConfig.getWxTemplateMsgAssistantUrl() + assistantCusPreDetailUrl.replace(COMPANY_UUID, companyUuid).replace(CUS_PRE_ID, customerPremises.getId().toString());
                wechatTemplateMsg.setUrl(url);
                String data = JSON.toJSONString(wechatTemplateMsg);
                TemplateMessageResult result = wechatTemplateMessageService.sendTemplate(assistantAccessToken, data);

                String systemId = SystemIdEnum.ASSISTANT.getCode();
                String receiveOpenId = openId;
                String modelType = String.valueOf(WxMessageTemplate.REPORT_CHECK_TEMPLATE_ID);
                String modelUuid = assistantWxMap.get(WxMessageTemplate.REPORT_CHECK_TEMPLATE_ID).getWxModelmsgId();
                buildWXFailureMsg(getPartnerId(reveivePartnerInfos, receiveOpenId), companyUuid, systemId, receiveOpenId, data, modelType, modelUuid, result, customerPremises.getId());

                Thread.sleep(1000L);
            } catch (InterruptedException ie) {
                logger.error("sendReportSuccessTemplateMsgForV10 InterruptedException---- 发送微信模板消息失败：{}", ie);
            } catch (Exception e) {
                logger.error("sendReportSuccessTemplateMsgForV10 ---- 发送微信模板消息失败：{}", e);
            }
        }
    }

    /**
     * 发送报备驳回模板消息 
     * 没有客户电话号码的~
     * @param agencyAccessToken
     * @param assistantAccessToken
     * @param customerPremises
     * @param wxMsgCommonDto
     */
    @Override
    @Async
    public void sendReportRefueTemplateMsg(String agencyAccessToken, String assistantAccessToken, CustomerPremises customerPremises, WxMsgCommonDto wxMsgCommonDto) {
        //发送微信模板消息
        if (StringUtils.isBlank(agencyAccessToken) && StringUtils.isBlank(assistantAccessToken)) {
            logger.info("sendReportRefueTemplateMsg ---- agencyAccessToken和assistantAccessToken为空，不发送模板消息");
            //return;
        }

        // 判断权限
//        boolean flag = wxmsgModelService.checkWeixinModelSet(null,wxMsgCommonDto.getCompanyUuid(),wxMsgCommonDto.getDomain(),WxMessageTemplate.REPORT_REJECT_TEMPLATE_ID);
//        if(!flag){
//            logger.info("sendReportRefueTemplateMsg ---- 发送微信模板消息失败：发送报备驳回模板消息开关未打开");
//            return;
//        }
        Premises premises = premisesService.selectSimpleById(customerPremises.getPremisesId());
        String companyUuid = wxMsgCommonDto.getCompanyUuid();
        Company company = companyService.selectById(premises.getCompanyId());
        if(StringUtils.isBlank(companyUuid)){
            logger.info("sendReportRefueTemplateMsg ---> companyuuid is null");
            companyUuid = company.getCompanyUuid();
        }
        //获取经纪人openId
        PartnerInfo agentPi = partnerInfoService.selectById(customerPremises.getStaffId());

        //add by zilong.liu 最后登录分销小程序跳转至小程序
        String modelSystemId = SystemIdEnum.AGENCY_h5.getCode();
        if (agentPi != null) {
        	agencyAccessToken = wxAccessTokenCacheUtils.getAccessTokenIfWeappMsg(company, agentPi.getLastLoginSystemId(), agencyAccessToken);
        	// 原固定使用分销助手的模板，现如果登录是分校小程序，需要使用小程序对应公众号配置的对应模板
        	modelSystemId = (SystemIdEnum.WEAPP_AGENCY.getCode().equals(agentPi.getLastLoginSystemId()) 
        			&& "1".equals(company.getEnableWeappMsg()))?  
        					SystemIdEnum.WEAPP_AGENCY_WX_ACCOUNTS.getCode(): SystemIdEnum.AGENCY_h5.getCode();
        }
		Map<Integer,WxmsgModel> agencyWxMap = subscriptionApiService.getSubscriptionModelMsg(companyUuid,wxMsgCommonDto.getDomain(),modelSystemId);
		//add by zilong.liu 最后登录分销小程序跳转至小程序
		if(agencyWxMap == null || agencyWxMap.size() == 0) {
        	logger.info("agencyWxMap is null, 请检查运营后台配置。companyUuid:{}", companyUuid);
        	return;
        }		
        //组装报备经纪人
        Map<String, List<String>> openIdMap = new HashMap<>();
        List<String> openIdList = new ArrayList<>();
        boolean agentPiFlag = agentPi != null && DelFlagEnum.UNDEL.getNo().equals(agentPi.getDelFlag())
                && PartnerStatusEnum.VALID.getNo().equals(agentPi.getStatus());
        openIdList.add(agentPiFlag ? agentPi.getWxOpenid() : "");
        openIdMap.put(AGENCY_SYSTEM,openIdList);
        //代报备人
        List<PartnerInfo> reveivePartnerInfos = new ArrayList<>();
        reveivePartnerInfos.add(agentPi);
        if(null != customerPremises && null != customerPremises.getPartnerId()){
            String replaceOpenId = partnerInfoService.getReplaceReporterOpenId(reveivePartnerInfos, customerPremises.getPartnerId());
            if(replaceOpenId != null) {
                openIdList = new ArrayList<>();
                openIdList.add(replaceOpenId);
                openIdMap.put(ASSISTANT_SYSTEM,openIdList);
            }
        }
        Map<Integer,WxmsgModel> assistantWxMap = subscriptionApiService.getSubscriptionModelMsg(companyUuid,wxMsgCommonDto.getDomain(),SystemIdEnum.ASSISTANT.getCode());
        if(assistantWxMap == null || assistantWxMap.size() == 0 || assistantWxMap.get(WxMessageTemplate.REPORT_REJECT_TEMPLATE_ID) == null) {
        	openIdMap.remove(ASSISTANT_SYSTEM);
        }
        for (String systemType : openIdMap.keySet()) {
            //agencyAccessToken或assistantAccessToken 为空说明获取失败或者未开通发送模板消息
            if((systemType.equals(AGENCY_SYSTEM) && StringUtils.isBlank(agencyAccessToken))
                    || (systemType.equals(ASSISTANT_SYSTEM) && StringUtils.isBlank(assistantAccessToken))) {
                continue;
            }
            List<String> openIdTempList = openIdMap.get(systemType);
            if(CollectionUtils.isEmpty(openIdTempList)){
                return;
            }
            for (String openId : openIdTempList) {
                try {
                    TreeMap<String, HashMap<String, String>> params = new TreeMap<>();
                    params.put("first", WechatTemplateMsg.item("有一条报备被驳回"));
                    params.put("keyword1", WechatTemplateMsg.item(agentPi.getAccountName()));
                    params.put("keyword2", WechatTemplateMsg.item("楼盘名称：" + premises.getName()));
                    params.put("keyword3", WechatTemplateMsg.item(StringUtils.isEmpty(wxMsgCommonDto.getRemark()) ? "未填写" : wxMsgCommonDto.getRemark()));
                    params.put("remark", WechatTemplateMsg.item("如有误，您可以提出报备申诉"));
                    WechatTemplateMsg wechatTemplateMsg = new WechatTemplateMsg();
                    String templateId = null;
                    String url = null;
                    if (systemType.equals(AGENCY_SYSTEM) && !agencyWxMap.isEmpty()) {
                        templateId = agencyWxMap.get(WxMessageTemplate.REPORT_REJECT_TEMPLATE_ID).getWxModelmsgId();
                        url = h5UrlConfig.getWxTemplateMsgAgencyUrl() + agencyCusPreDetailUrl;
                        //add by zilong.liu 最后登录分销小程序跳转至小程序
                        url = url.replace(COMPANY_UUID, companyUuid).replace(CUS_PRE_ID, customerPremises.getId().toString());
                        wechatTemplateMsg.setUrl(url);
                        if(agentPi != null && company != null) {
                        	addMiniProgram(agentPi.getLastLoginSystemId(), companyUuid, company.getEnableWeappMsg(), wechatTemplateMsg, customerPremises.getId());
                        }
                        //add by zilong.liu 最后登录分销小程序跳转至小程序
                    } else {
                        templateId = assistantWxMap.get(WxMessageTemplate.REPORT_REJECT_TEMPLATE_ID).getWxModelmsgId();
                        url = h5UrlConfig.getWxTemplateMsgAssistantUrl() + assistantCusPreDetailUrl;
                        url = url.replace(COMPANY_UUID, companyUuid).replace(CUS_PRE_ID, customerPremises.getId().toString());
                        wechatTemplateMsg.setUrl(url);
                    }
                    wechatTemplateMsg.setTemplate_id(templateId);
                    wechatTemplateMsg.setTouser(openId);

                    wechatTemplateMsg.setData(params);
                    String data = JSON.toJSONString(wechatTemplateMsg);
                    TemplateMessageResult result = wechatTemplateMessageService.sendTemplate(systemType.equals(AGENCY_SYSTEM)?agencyAccessToken:assistantAccessToken, data);
                 
                    // update by zilong.liu  分销小程序渠道变更
                    String systemId = modelSystemId;
                    if(systemType.equals(ASSISTANT_SYSTEM)) {
                    	systemId = SystemIdEnum.ASSISTANT.getCode();
                    }
//                    String systemId = systemType.equals(AGENCY_SYSTEM)?SystemIdEnum.AGENCY_h5.getCode(): SystemIdEnum.ASSISTANT.getCode();
                    // update by zilong.liu  分销小程序渠道变更
                    
                    String receiveOpenId = openId;
                    String modelType = String.valueOf(WxMessageTemplate.REPORT_REJECT_TEMPLATE_ID);
                    String modelUuid = templateId;
                    buildWXFailureMsg(getPartnerId(reveivePartnerInfos, receiveOpenId), companyUuid, systemId, receiveOpenId, data, modelType, modelUuid, result, customerPremises.getId());

                    Thread.sleep(1000L);
                } catch (InterruptedException ie) {
                    logger.error("sendReportRefueTemplateMsg InterruptedException---- 发送微信模板消息失败：{}", ie);
                } catch (Exception e) {
                    logger.error("sendReportRefueTemplateMsg ---- 发送微信模板消息失败：{}", e);
                }
            }
        }
    }

    /**
     * 发送报备审核模板模板消息
     *  -- 推送对象：驻守该楼盘的案场驻守人员
     *  需要发送给案场，已处理
     * @param assistantAccessToken
     * @param companyUuid
     * @param domain
     * @param cusId
     * @param premisesId
     */
    @Override
    @Async
    public void sendReportCheckTemplateMsg(String assistantAccessToken, String companyUuid, String domain,
                                           Long cusId, String premisesId, String staffId, String cusName, String cusPhone, String visitTime) {
        if (StringUtils.isBlank(assistantAccessToken)) {
            logger.info("sendReportCheckTemplateMsg ---- assistantAccessToken为空，不发送模板消息");
            return;
        }
        if(null == cusId) {
            logger.info("sendReportCheckTemplateMsg ---- 报备Id 不能为空！");
            return;
        }
        if(StringUtils.isBlank(premisesId)) {
            logger.info("sendReportCheckTemplateMsg ---- 楼盘ID不能为空！");
            return;
        }
        if(StringUtils.isBlank(companyUuid) && StringUtils.isBlank(domain)) {
            logger.info("sendReportCheckTemplateMsg ---- companyUuid和domain不能同时为空！");
            return;
        }
        if(StringUtils.isBlank(staffId)) {
            logger.info("sendReportCheckTemplateMsg ---- 经纪人ID不能为空！");
            return;
        }
        // 判断权限
//        boolean flag = wxmsgModelService.checkWeixinModelSet(null,companyUuid,domain,WxMessageTemplate.REPORT_CHECK_TEMPLATE_ID);
//        if(!flag){
//            logger.info("sendVisitSuccessTemplateMsg ---- 发送微信模板消息失败：发送报备审核模板开关未打开");
//            return;
//        }

        //获取经纪人信息
        PartnerInfo agentPi = partnerInfoService.selectById(Long.valueOf(staffId));
        if(agentPi == null) {
            logger.info("sendReportCheckTemplateMsg ---- 获取经纪人信息失败！");
            return;
        }

        //获取接收微信模板消息驻场人员openid
        CaseMemberDto caseMemberDto = new CaseMemberDto();
        caseMemberDto.setPremisesId(Long.valueOf(premisesId));
        List<PartnerInfo> partnerInfoList = caseMemberService.selectListForWxMsg(caseMemberDto);
        // 筛选出有权限的用户
        partnerInfoList = filterPartnerByPermission(partnerInfoList, agentPi);
        List<String> assignOpenIdList = null;
        if(partnerInfoList != null && partnerInfoList.size() > 0) {
            assignOpenIdList = partnerInfoList.stream().filter(partnerInfo -> partnerInfo.getWxOpenid() != null).map(PartnerInfo::getWxOpenid).collect(Collectors.toList());
        }
        if (assignOpenIdList == null) {
            logger.info("sendReportCheckTemplateMsg ---- 获取驻场人员openId失败或者数据为空！");
            return;
        }
        List<PartnerInfo> reveivePartnerInfos = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(partnerInfoList)) {
            reveivePartnerInfos.addAll(partnerInfoList);
        }
        List<String> hideWxOpenIds = getHideWxOpenIds(assignOpenIdList);
        List<String> hideAgentPhoneOpenIds = getHideAgentPhoneOpenIds(assignOpenIdList);
        //楼盘信息
        PremisesDto premisesDto = new PremisesDto();
        premisesDto.setId(Long.valueOf(premisesId));
        List<Premises> premisesList = premisesService.selectIdListByDto(premisesDto);
        if(premisesList == null || premisesList.size() == 0) {
            logger.info("sendReportCheckTemplateMsg ---- 未获取到楼盘信息！");
            return;
        }
        Premises premises = premisesList.get(0);
        Company company = companyService.selectById(premises.getCompanyId());
        if(null == company) {
            logger.info("sendReportCheckTemplateMsg ---- 未获取到商户信息！");
            return;
        }
        companyUuid = company.getCompanyUuid();
        //获取对接人
        DepartmentDto departDto = departmentDao.getPrincipalForWxMsg(Long.valueOf(staffId));
        String principalName = departDto != null ? departDto.getPrincipalName() : "";

        //经纪人公司名称
        Organization organization = companyService.getOrganizationInfo(agentPi.getHigherid(), agentPi.getDeptId());
        //获取微信模板配置失败
        Map<Integer,WxmsgModel> assistantWxMap = subscriptionApiService.getSubscriptionModelMsg(companyUuid
                , domain, SystemIdEnum.ASSISTANT.getCode());
        if (assistantWxMap == null || assistantWxMap.size() == 0 || assistantWxMap.get(WxMessageTemplate.REPORT_CHECK_TEMPLATE_ID) == null) {
            logger.info("sendReportCheckTemplateMsg ---- 获取微信模板配置失败！");
            return;
        }
        //报备时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        CustomerPremises cusPre = customerPremisesService.selectById(cusId);
        String reportTime = sdf.format(cusPre.getCreateTime());

        for (String openId : assignOpenIdList) {
            logger.info("openId =========" + openId);
            logger.info("assistantAccessToken =========" + assistantAccessToken);
            try {
                TreeMap<String, HashMap<String, String>> params = new TreeMap<>();
                params.put("first", WechatTemplateMsg.item("有一条新的报备通知，请查看"));
                params.put("keyword1", WechatTemplateMsg.item(premises.getName() + " 对接人" + principalName));
                String realPhone = getRealPhoneByCaseMemberAuth(hideWxOpenIds, cusPhone, openId, ASSISTANT_SYSTEM, Long.valueOf(premisesId));
                params.put("keyword2", WechatTemplateMsg.item(cusName + " " + realPhone));
                params.put("keyword3", WechatTemplateMsg.item(reportTime));
                String agentPhone = getAgentPhoneByCaseMemberAuth(hideAgentPhoneOpenIds, agentPi.getPhone(), openId, ASSISTANT_SYSTEM, Long.valueOf(premisesId));
                params.put("keyword4", WechatTemplateMsg.item(
                        organization.getCompanyName() + " - "
                        + organization.getDepartmentName() + " "
                        //+ organization.getGroupName() + " "
                        //+ organization.getStoreName() + " "
                        + agentPi.getAccountName() + " "
                        + agentPhone));
                // 预计到访时间 V10可以传值为空
                if(StringUtils.isNotEmpty(visitTime)){
                    params.put("remark", WechatTemplateMsg.item("到访时间：" + visitTime + "\n烦请审批通过，感谢！"));
                }else{
                    params.put("remark", WechatTemplateMsg.item("\n烦请审批通过，感谢！"));
                }
                WechatTemplateMsg wechatTemplateMsg = new WechatTemplateMsg();
                if(assistantWxMap.get(WxMessageTemplate.REPORT_CHECK_TEMPLATE_ID) == null) {
                	logger.info("WxTemplateMsgServiceImpl->sendReportCheckTemplateMsg:assistantWxMap:{}", assistantWxMap);
                	continue;
                }
                wechatTemplateMsg.setTemplate_id(assistantWxMap.get(WxMessageTemplate.REPORT_CHECK_TEMPLATE_ID).getWxModelmsgId());
                wechatTemplateMsg.setTouser(openId);
                logger.info(h5UrlConfig.getWxTemplateMsgAssistantUrl() + "--->" + companyUuid + "---->" + cusId);
                String url = h5UrlConfig.getWxTemplateMsgAssistantUrl() + assistantCusPreDetailUrl.replace(COMPANY_UUID, companyUuid).replace(CUS_PRE_ID, cusId.toString());
                wechatTemplateMsg.setUrl(url);
                wechatTemplateMsg.setData(params);
                String data = JSON.toJSONString(wechatTemplateMsg);
                TemplateMessageResult result = wechatTemplateMessageService.sendTemplate(assistantAccessToken, data);

                String systemId = SystemIdEnum.ASSISTANT.getCode();
                String receiveOpenId = openId;
                String modelType = String.valueOf(WxMessageTemplate.REPORT_CHECK_TEMPLATE_ID);
                String modelUuid = assistantWxMap.get(WxMessageTemplate.REPORT_CHECK_TEMPLATE_ID).getWxModelmsgId();
                buildWXFailureMsg(getPartnerId(reveivePartnerInfos, receiveOpenId), companyUuid, systemId, receiveOpenId, data, modelType, modelUuid, result, cusId);

                Thread.sleep(1000L);
            } catch (InterruptedException ie) {
                logger.error("sendReportCheckTemplateMsg InterruptedException---- 发送微信模板消息失败：{}", ie);
            } catch (Exception e) {
                logger.error("sendReportCheckTemplateMsg ---- 发送微信模板消息失败：{}", e);
            }
        }
    }

    /**
     * 发送报备审核模板模板消息
     *  -- 推送对象：驻守该楼盘的案场驻守人员
     *  需要发送给案场，已处理
     * @param assistantAccessToken
     * @param companyUuid
     * @param domain
     * @param cusId
     * @param premisesId
     */
    @Override
    @Async
    public void sendVisitCheckTemplateMsg(String assistantAccessToken, String companyUuid, String domain,
                                           Long cusId, String premisesId, String staffId, String cusName, String cusPhone, String visitTime) {
        if (StringUtils.isBlank(assistantAccessToken)) {
            logger.info("sendVisitCheckTemplateMsg ---- assistantAccessToken为空，不发送模板消息");
            return;
        }
        if(StringUtils.isBlank(premisesId)) {
            logger.info("sendVisitCheckTemplateMsg ---- 楼盘ID不能为空！");
            return;
        }
        if(StringUtils.isBlank(companyUuid) && StringUtils.isBlank(domain)) {
            logger.info("sendVisitCheckTemplateMsg ---- companyUuid和domain不能同时为空！");
            return;
        }
        if(StringUtils.isBlank(staffId)) {
            logger.info("sendVisitCheckTemplateMsg ---- 经纪人ID不能为空！");
            return;
        }
        // 判断权限
//        boolean flag = wxmsgModelService.checkWeixinModelSet(null,companyUuid,domain,WxMessageTemplate.VISIT_CHECK_TEMPLATE_ID);
//        if(!flag){
//            logger.info("sendVisitCheckTemplateMsg ---- 发送微信模板消息失败：发送报备审核模板开关未打开");
//            return;
//        }

        //获取经纪人信息
        PartnerInfo agentPi = partnerInfoService.selectById(Long.valueOf(staffId));
        if(agentPi == null) {
            logger.info("sendVisitCheckTemplateMsg ---- 获取经纪人信息失败！");
            return;
        }

        //获取接收微信模板消息驻场人员openid
        CaseMemberDto caseMemberDto = new CaseMemberDto();
        caseMemberDto.setPremisesId(Long.valueOf(premisesId));
        List<PartnerInfo> partnerInfoList = caseMemberService.selectListForWxMsg(caseMemberDto);
        // 筛选出有权限的用户
        partnerInfoList = filterPartnerByPermission(partnerInfoList, agentPi);
        List<String> assignOpenIdList = null;
        if(partnerInfoList != null && partnerInfoList.size() > 0) {
            assignOpenIdList = partnerInfoList.stream().filter(partnerInfo -> partnerInfo.getWxOpenid() != null).map(PartnerInfo::getWxOpenid).collect(Collectors.toList());
        }
        if (assignOpenIdList == null) {
            logger.info("sendVisitCheckTemplateMsg ---- 获取驻场人员openId失败或者数据为空！");
            return;
        }
        List<PartnerInfo> reveivePartnerInfos = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(partnerInfoList)) {
            reveivePartnerInfos.addAll(partnerInfoList);
        }
        List<String> hideWxOpenIds = getHideWxOpenIds(assignOpenIdList);
        List<String> hideAgentPhoneOpenIds = getHideAgentPhoneOpenIds(assignOpenIdList);
        //楼盘信息
        PremisesDto premisesDto = new PremisesDto();
        premisesDto.setId(Long.valueOf(premisesId));
        List<Premises> premisesList = premisesService.selectIdListByDto(premisesDto);
        if(premisesList == null || premisesList.size() == 0) {
            logger.info("sendVisitCheckTemplateMsg ---- 未获取到楼盘信息！");
            return;
        }
        Premises premises = premisesList.get(0);
        Company company = companyService.selectById(premises.getCompanyId());
        if(null == company) {
            logger.info("sendVisitCheckTemplateMsg ---- 未获取到商户信息！");
            return;
        }
        companyUuid = company.getCompanyUuid();
        //获取对接人
        DepartmentDto departDto = departmentDao.getPrincipalForWxMsg(Long.valueOf(staffId));
        String principalName = departDto != null ? departDto.getPrincipalName() : "";

        //经纪人公司名称
        Organization organization = companyService.getOrganizationInfo(agentPi.getHigherid(), agentPi.getDeptId());
        //获取微信模板配置失败
        Map<Integer,WxmsgModel> assistantWxMap = subscriptionApiService.getSubscriptionModelMsg(companyUuid
                , domain, SystemIdEnum.ASSISTANT.getCode());
        if (assistantWxMap == null || assistantWxMap.size() == 0 || assistantWxMap.get(WxMessageTemplate.VISIT_CHECK_TEMPLATE_ID) == null) {
            logger.info("sendVisitCheckTemplateMsg ---- 获取微信模板配置失败！");
            return;
        }
        for (String openId : assignOpenIdList) {
            logger.info("openId =========" + openId);
            logger.info("assistantAccessToken =========" + assistantAccessToken);
            try {
                TreeMap<String, HashMap<String, String>> params = new TreeMap<>();
                params.put("first",WechatTemplateMsg.item("到访审核提醒"));
                String realPhone = getRealPhoneByCaseMemberAuth(hideWxOpenIds, cusPhone, openId, ASSISTANT_SYSTEM, Long.valueOf(premisesId));
                params.put("keyword1",WechatTemplateMsg.item(cusName + " " + realPhone));
                params.put("keyword2",WechatTemplateMsg.item(premises.getName()));
                params.put("keyword3",WechatTemplateMsg.item("到访待审"));
                String agentPhone = getAgentPhoneByCaseMemberAuth(hideAgentPhoneOpenIds, agentPi.getPhone(), openId, ASSISTANT_SYSTEM, Long.valueOf(premisesId));
                params.put("keyword4",WechatTemplateMsg.item(
                        organization.getCompanyName() + " - "
                        + organization.getDepartmentName() + " "
                        //+ organization.getGroupName() + " "
                        //+ organization.getStoreName() + " "
                        + agentPi.getAccountName() + " "
                        + agentPhone));
                // 预计到访时间 V10可以传值为空
                if(StringUtils.isNotEmpty(visitTime)){
                    params.put("remark",WechatTemplateMsg.item("到访时间：" + visitTime + "，请及时进行到访审核操作"));
                }else{
                    params.put("remark", WechatTemplateMsg.item("\n请及时进行到访审核操作！"));
                }
                WechatTemplateMsg wechatTemplateMsg = new WechatTemplateMsg();
                wechatTemplateMsg.setTemplate_id(assistantWxMap.get(WxMessageTemplate.VISIT_CHECK_TEMPLATE_ID).getWxModelmsgId());
                wechatTemplateMsg.setTouser(openId);
                String url = h5UrlConfig.getWxTemplateMsgAssistantUrl() + assistantCusPreDetailUrl.replace(COMPANY_UUID, companyUuid).replace(CUS_PRE_ID, cusId.toString());
                wechatTemplateMsg.setUrl(url);
                wechatTemplateMsg.setData(params);
                String data = JSON.toJSONString(wechatTemplateMsg);
                TemplateMessageResult result = wechatTemplateMessageService.sendTemplate(assistantAccessToken, data);

                String systemId = SystemIdEnum.ASSISTANT.getCode();
                String receiveOpenId = openId;
                String modelType = String.valueOf(WxMessageTemplate.VISIT_CHECK_TEMPLATE_ID);
                String modelUuid = assistantWxMap.get(WxMessageTemplate.VISIT_CHECK_TEMPLATE_ID).getWxModelmsgId();
                buildWXFailureMsg(getPartnerId(reveivePartnerInfos, receiveOpenId), companyUuid, systemId, receiveOpenId, data, modelType, modelUuid, result, cusId);

                Thread.sleep(1000L);
            } catch (InterruptedException ie) {
                logger.error("sendVisitCheckTemplateMsg InterruptedException---- 发送微信模板消息失败：{}", ie);
            } catch (Exception e) {
                logger.error("sendVisitCheckTemplateMsg ---- 发送微信模板消息失败：{}", e);
            }
        }
    }

    /**
     * 发送报备申诉提醒模板消息
     * 需要给案场发送消息，已处理
     * @param assistantAccessToken
     * @param companyUuid
     * @param domain
     * @param cusPreId
     * @param premisesId
     * @param staffId
     * @param cusName
     * @param cusPhone
     * @param visitTime
     */
    @Override
    @Async
    public void sendReportAppealTemplateMsg(String assistantAccessToken, String companyUuid, String domain,
                                            Long cusPreId, String premisesId, String staffId, String cusName, String cusPhone, String visitTime) {
        if (StringUtils.isBlank(assistantAccessToken)) {
            logger.info("sendReportAppealTemplateMsg ---- assistantAccessToken为空，不发送模板消息");
            return;
        }
        if(StringUtils.isBlank(premisesId)) {
            logger.info("sendReportAppealTemplateMsg ---- 楼盘ID不能为空！");
            return;
        }
        if(StringUtils.isBlank(companyUuid) && StringUtils.isBlank(domain)) {
            logger.info("sendReportAppealTemplateMsg ---- companyUuid和domain不能同时为空！");
            return;
        }
        if(StringUtils.isBlank(staffId)) {
            logger.info("sendReportAppealTemplateMsg ---- 经纪人ID不能为空！");
            return;
        }
        //
        // 判断权限
//        boolean flag = wxmsgModelService.checkWeixinModelSet(null,companyUuid,domain,WxMessageTemplate.REPORT_APPEAL_TEMPLATE_ID);
//        if(!flag){
//            logger.info("sendReportAppealTemplateMsg ---- 发送微信模板消息失败：发送报备申诉提醒模板开关未打开");
//            return;
//        }

        //获取经纪人信息
        PartnerInfo agentPi = partnerInfoService.selectById(Long.valueOf(staffId));
        if(agentPi == null) {
            logger.info("sendReportAppealTemplateMsg ---- 获取经纪人信息失败！");
            return;
        }

        //获取接收微信模板消息驻场人员openid
        CaseMemberDto caseMemberDto = new CaseMemberDto();
        caseMemberDto.setPremisesId(Long.valueOf(premisesId));
        List<PartnerInfo> partnerInfoList = caseMemberService.selectListForWxMsg(caseMemberDto);
        // 筛选出有权限的用户
        partnerInfoList = filterPartnerByPermission(partnerInfoList, agentPi);
        List<String> assignOpenIdList = null;
        if(partnerInfoList != null && partnerInfoList.size() > 0) {
            assignOpenIdList = partnerInfoList.stream().filter(partnerInfo -> partnerInfo.getWxOpenid() != null).map(PartnerInfo::getWxOpenid).collect(Collectors.toList());
        }
        if (assignOpenIdList == null) {
            logger.info("sendReportAppealTemplateMsg ---- 获取驻场人员openId失败或者数据为空！");
            return;
        }
        List<String> hideWxOpenIds = getHideWxOpenIds(assignOpenIdList);
        List<String> hideAgentPhoneOpenIds = getHideAgentPhoneOpenIds(assignOpenIdList);
        List<PartnerInfo> reveivePartnerInfos = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(partnerInfoList)) {
            reveivePartnerInfos.addAll(partnerInfoList);
        }
        //楼盘信息
        PremisesDto premisesDto = new PremisesDto();
        premisesDto.setId(Long.valueOf(premisesId));
        List<Premises> premisesList = premisesService.selectIdListByDto(premisesDto);
        if(premisesList == null || premisesList.size() == 0) {
            logger.info("sendReportAppealTemplateMsg ---- 未获取到楼盘信息！");
            return;
        }
        Premises premises = premisesList.get(0);
        //获取对接人
        DepartmentDto departDto = departmentDao.getPrincipalForWxMsg(Long.valueOf(staffId));
        String principalName = departDto != null ? departDto.getPrincipalName() : "";

        //经纪人公司名称
        Organization organization = companyService.getOrganizationInfo(agentPi.getHigherid(), agentPi.getDeptId());
        //获取微信模板配置失败
        Map<Integer,WxmsgModel> assistantWxMap = subscriptionApiService.getSubscriptionModelMsg(companyUuid
                , domain, SystemIdEnum.ASSISTANT.getCode());
        if (assistantWxMap == null || assistantWxMap.size() == 0 || assistantWxMap.get(WxMessageTemplate.REPORT_APPEAL_TEMPLATE_ID) == null) {
            logger.info("sendReportAppealTemplateMsg ---- 获取微信模板配置失败！");
            return;
        }
        //报备时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        CustomerPremises cusPre = customerPremisesService.selectById(cusPreId);
        String reportTime = sdf.format(cusPre.getCreateTime());

        if(StringUtils.isBlank(companyUuid)){
            logger.info("sendReportAppealTemplateMsg ---> companyuuid is null");
            Company company = companyService.selectById(premises.getCompanyId());
            companyUuid = company.getCompanyUuid();
        }
        for (String openId : assignOpenIdList) {
            try {
                TreeMap<String, HashMap<String, String>> params = new TreeMap<>();
                params.put("first", WechatTemplateMsg.item("有一条报备申诉通知，请查看"));
                params.put("keyword1", WechatTemplateMsg.item(premises.getName() + " 对接人" + principalName));
                String realPhone = getRealPhoneByCaseMemberAuth(hideWxOpenIds, cusPhone, openId, ASSISTANT_SYSTEM, Long.valueOf(premisesId));
                params.put("keyword2", WechatTemplateMsg.item(cusName + " " + realPhone));
                params.put("keyword3", WechatTemplateMsg.item(reportTime));
                String agentPhone = getAgentPhoneByCaseMemberAuth(hideAgentPhoneOpenIds, agentPi.getPhone(), openId, ASSISTANT_SYSTEM, Long.valueOf(premisesId));
                params.put("keyword4", WechatTemplateMsg.item(
                        organization.getCompanyName() + " - "
                        + organization.getDepartmentName() + " "
                        //+ organization.getGroupName() + " "
                        //+ organization.getStoreName() + " "
                        + agentPi.getAccountName() + " "
                        + agentPhone));
                // 预计到访时间 V10可以传值为空
                if(StringUtils.isNotEmpty(visitTime)){
                    params.put("remark", WechatTemplateMsg.item("到访时间：" + visitTime + "\n烦请审批通过，感谢！"));
                }else{
                    params.put("remark", WechatTemplateMsg.item("\n烦请审批通过，感谢！"));
                }
                WechatTemplateMsg wechatTemplateMsg = new WechatTemplateMsg();
                wechatTemplateMsg.setTemplate_id(assistantWxMap.get(WxMessageTemplate.REPORT_APPEAL_TEMPLATE_ID).getWxModelmsgId());
                wechatTemplateMsg.setTouser(openId);
                String url = h5UrlConfig.getWxTemplateMsgAssistantUrl() + assistantCusPreDetailUrl.replace(COMPANY_UUID, companyUuid).replace(CUS_PRE_ID, cusPreId.toString());
                wechatTemplateMsg.setUrl(url);
                wechatTemplateMsg.setData(params);
                String data = JSON.toJSONString(wechatTemplateMsg);
                TemplateMessageResult result = wechatTemplateMessageService.sendTemplate(assistantAccessToken, data);

                String systemId = SystemIdEnum.ASSISTANT.getCode();
                String receiveOpenId = openId;
                String modelType = String.valueOf(WxMessageTemplate.REPORT_APPEAL_TEMPLATE_ID);
                String modelUuid = assistantWxMap.get(WxMessageTemplate.REPORT_APPEAL_TEMPLATE_ID).getWxModelmsgId();
                buildWXFailureMsg(getPartnerId(reveivePartnerInfos, receiveOpenId), companyUuid, systemId, receiveOpenId, data, modelType, modelUuid, result, cusPreId);

                Thread.sleep(1000L);
            } catch (InterruptedException ie) {
                logger.error("sendReportAppealTemplateMsg InterruptedException---- 发送微信模板消息失败：{}", ie);
            } catch (Exception e) {
                logger.error("sendReportAppealTemplateMsg ---- 发送微信模板消息失败：{}", e);
            }
        }
    }

    /**
     * 发送认筹成功模板消息
     * 需要给案场发送信息、已处理
     * @param agencyAccessToken
     * @param assistantAccessToken
     * @param companyUuid
     * @param domain
     * @param cusPreId
     * @param premisesId
     * @param staffId
     * @param cusName
     * @param cusPhone
     */
    @Override
    @Async
    public void sendPayDepositSuccessTemplateMsg(String agencyAccessToken, String assistantAccessToken, String companyUuid, String domain,
                                                 Long cusPreId, String premisesId, String staffId, String cusName, String cusPhone) {
        if (StringUtils.isBlank(assistantAccessToken) && StringUtils.isBlank(agencyAccessToken)) {
            logger.info("sendPayDepositSuccessTemplateMsg ---- assistantAccessToken且agencyAccessToken为空，不发送模板消息");
            return;
        }
        if (StringUtils.isBlank(premisesId)) {
            logger.info("sendPayDepositSuccessTemplateMsg ---- 楼盘ID不能为空！");
            return;
        }
        if (StringUtils.isBlank(companyUuid) && StringUtils.isBlank(domain)) {
            logger.info("sendPayDepositSuccessTemplateMsg ---- companyUuid和domain不能同时为空！");
            return;
        }
        if (StringUtils.isBlank(staffId)) {
            logger.info("sendPayDepositSuccessTemplateMsg ---- 经纪人ID不能为空！");
            return;
        }
        // 判断权限
//        boolean flag = wxmsgModelService.checkWeixinModelSet(null,companyUuid,domain,WxMessageTemplate.PAY_DEPOSIT_SUCCESS_TEMPLATE_ID);
//        if(!flag){
//            logger.info("sendPayDepositSuccessTemplateMsg ---- 发送微信模板消息失败：发送认筹成功模板开关未打开");
//            return;
//        }
        //获取经纪人openId
        PartnerInfoDto partnerInfoDto = new PartnerInfoDto();
        partnerInfoDto.setId(Long.valueOf(staffId));
        partnerInfoDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
        partnerInfoDto.setStatus(PartnerStatusEnum.VALID.getNo());
        PartnerInfo agentPi = partnerInfoService.selectByDto(partnerInfoDto);
        //获取接收微信模板消息驻场人员openid
        CaseMemberDto caseMemberDto = new CaseMemberDto();
        caseMemberDto.setPremisesId(Long.valueOf(premisesId));
        List<PartnerInfo> partnerInfoList = caseMemberService.selectListForWxMsg(caseMemberDto);
        // 筛选出有权限的用户
        partnerInfoList = filterPartnerByPermission(partnerInfoList, agentPi);
        List<String> assignOpenIdList = null;
        if(partnerInfoList != null && partnerInfoList.size() > 0) {
            assignOpenIdList = partnerInfoList.stream().filter(partnerInfo -> partnerInfo.getWxOpenid() != null).map(PartnerInfo::getWxOpenid).collect(Collectors.toList());
        }
        if (assignOpenIdList == null) {
            logger.info("sendPayDepositSuccessTemplateMsg ---- 获取驻场人员openId失败或者数据为空！");
            return;
        }
        List<String> hideWxOpenIds = getHideWxOpenIds(assignOpenIdList);
        //组装数据
        Map<String, List<String>> openIdMap = new HashMap<>();
        List<String> openIdList = new ArrayList<>();
        openIdList.add(agentPi != null ? agentPi.getWxOpenid() : "");
        List<PartnerInfo> reveivePartnerInfos = new ArrayList<>();
        reveivePartnerInfos.add(agentPi);
        if(CollectionUtils.isNotEmpty(partnerInfoList)) {
            reveivePartnerInfos.addAll(partnerInfoList);
        }
        openIdMap.put(AGENCY_SYSTEM, openIdList);
        openIdMap.put(ASSISTANT_SYSTEM, assignOpenIdList);

        //楼盘信息
        PremisesDto premisesDto = new PremisesDto();
        premisesDto.setId(Long.valueOf(premisesId));
        List<Premises> premisesList = premisesService.selectIdListByDto(premisesDto);
        if (premisesList == null || premisesList.size() == 0) {
            logger.info("sendPayDepositSuccessTemplateMsg ---- 未获取到楼盘信息！");
            return;
        }
        Premises premises = premisesList.get(0);
        //获取商户名称
        Company company = companyService.selectById(premises.getCompanyId());
        if (null == company) {
            logger.info("sendPayDepositSuccessTemplateMsg ---- 未获取到获取商户名称！");
            return;
        }
        companyUuid = company.getCompanyUuid();
        
        //add by zilong.liu update for 分销小程序消息
        String modelSystemId = SystemIdEnum.AGENCY_h5.getCode();
        if (agentPi != null) {
        	agencyAccessToken = wxAccessTokenCacheUtils.getAccessTokenIfWeappMsg(company, agentPi.getLastLoginSystemId(), agencyAccessToken);
        	// 原固定使用分销助手的模板，现如果登录是分校小程序，需要使用小程序对应公众号配置的对应模板
        	modelSystemId = (SystemIdEnum.WEAPP_AGENCY.getCode().equals(agentPi.getLastLoginSystemId()) 
        			&& "1".equals(company.getEnableWeappMsg()))? 
        					SystemIdEnum.WEAPP_AGENCY_WX_ACCOUNTS.getCode(): SystemIdEnum.AGENCY_h5.getCode();
        }
		//add by zilong.liu update for 分销小程序消息
        
        //获取微信模板配置失败
        Map<Integer,WxmsgModel> agencyWxMap = subscriptionApiService.getSubscriptionModelMsg(companyUuid
                , domain,modelSystemId);
        if(agencyWxMap == null || agencyWxMap.size() == 0) {
        	logger.info("agencyWxMap is null, 请检查运营后台配置:companyUuid{}", companyUuid);
        	return;
        }
        Map<Integer, WxmsgModel> assistantWxMap = subscriptionApiService.getSubscriptionModelMsg(companyUuid
                , domain, SystemIdEnum.ASSISTANT.getCode());
        if (assistantWxMap == null || assistantWxMap.size() == 0 || assistantWxMap.get(WxMessageTemplate.PAY_DEPOSIT_SUCCESS_TEMPLATE_ID) == null) {
            	openIdMap.remove(ASSISTANT_SYSTEM);
        }

        for (String systemType : openIdMap.keySet()) {
            //agencyAccessToken 或 assistantAccessToken 为空说明获取失败或者未开通发送模板消息
            if((systemType.equals(AGENCY_SYSTEM) && StringUtils.isBlank(agencyAccessToken))
                    || (systemType.equals(ASSISTANT_SYSTEM) && StringUtils.isBlank(assistantAccessToken))) {
                logger.info("sendPayDepositSuccessTemplateMsg ---- agencyAccessToken或assistantAccessToken为空！");
                continue;
            }
            List<String> openIdTempList = openIdMap.get(systemType);
            if(CollectionUtils.isEmpty(openIdTempList)){
                return;
            }
            for (String openId : openIdTempList) {
                try {
                    TreeMap<String, HashMap<String, String>> params = new TreeMap<>();
                    params.put("first", WechatTemplateMsg.item("恭喜认筹成功！", "#000000"));
                    String realPhone = getRealPhoneByCaseMemberAuth(hideWxOpenIds, cusPhone, openId, systemType, Long.valueOf(premisesId));
                    params.put("keyword1", WechatTemplateMsg.item(cusName + " " + realPhone));
                    params.put("keyword2", WechatTemplateMsg.item(premises.getName()));
                    params.put("keyword3", WechatTemplateMsg.item("认筹成功"));
                    params.put("keyword4", WechatTemplateMsg.item(company.getCompanyName()));
                    params.put("remark", WechatTemplateMsg.item("请及时跟进后续业务"));
                    WechatTemplateMsg wechatTemplateMsg = new WechatTemplateMsg();
                    String templateId = null;
                    String url = null;
                    if (systemType.equals(AGENCY_SYSTEM) && !agencyWxMap.isEmpty()) {
                        templateId = agencyWxMap.get(WxMessageTemplate.PAY_DEPOSIT_SUCCESS_TEMPLATE_ID).getWxModelmsgId();
                        url = h5UrlConfig.getWxTemplateMsgAgencyUrl() + agencyCusPreDetailUrl;
                        url = url.replace(COMPANY_UUID, companyUuid).replace(CUS_PRE_ID, cusPreId.toString());
                        //add by zilong.liu 最后登录分销小程序跳转至小程序
						wechatTemplateMsg.setUrl(url);
						if(agentPi != null && company != null) {
							addMiniProgram(agentPi.getLastLoginSystemId(), companyUuid, company.getEnableWeappMsg(), wechatTemplateMsg, cusPreId);
						}
                        //add by zilong.liu 最后登录分销小程序跳转至小程序
                    } else {
                        templateId = assistantWxMap.get(WxMessageTemplate.PAY_DEPOSIT_SUCCESS_TEMPLATE_ID).getWxModelmsgId();
                        url = h5UrlConfig.getWxTemplateMsgAssistantUrl() + assistantCusPreDetailUrl;
                        url = url.replace(COMPANY_UUID, companyUuid).replace(CUS_PRE_ID, cusPreId.toString());
                        wechatTemplateMsg.setUrl(url);
                    }
                    wechatTemplateMsg.setTemplate_id(templateId);
                    wechatTemplateMsg.setTouser(openId);
                    wechatTemplateMsg.setData(params);
                    String data = JSON.toJSONString(wechatTemplateMsg);
                    TemplateMessageResult result = wechatTemplateMessageService.sendTemplate(systemType.equals(AGENCY_SYSTEM)?agencyAccessToken:assistantAccessToken, data);

                    // update by zilong.liu  分销小程序渠道变更
                    String systemId = modelSystemId;
                    if(systemType.equals(ASSISTANT_SYSTEM)) {
                    	systemId = SystemIdEnum.ASSISTANT.getCode();
                    }
//                    String systemId = systemType.equals(AGENCY_SYSTEM)?SystemIdEnum.AGENCY_h5.getCode(): SystemIdEnum.ASSISTANT.getCode();
                    // update by zilong.liu  分销小程序渠道变更
//                    String systemId = systemType.equals(AGENCY_SYSTEM)?SystemIdEnum.AGENCY_h5.getCode():SystemIdEnum.ASSISTANT.getCode();
                    String receiveOpenId = openId;
                    String modelType = String.valueOf(WxMessageTemplate.PAY_DEPOSIT_SUCCESS_TEMPLATE_ID);
                    String modelUuid = templateId;
                    buildWXFailureMsg(getPartnerId(reveivePartnerInfos, receiveOpenId), companyUuid, systemId, receiveOpenId, data, modelType, modelUuid, result, cusPreId);

                    Thread.sleep(1000L);
                } catch (InterruptedException ie) {
                    logger.error("sendPayDepositSuccessTemplateMsg InterruptedException---- 发送微信模板消息失败：{}", ie);
                } catch (Exception e) {
                    logger.error("sendPayDepositSuccessTemplateMsg ---- 发送微信模板消息失败：{}", e);
                }
            }
        }
    }

    /**
     * 发送认购成功提醒模板消息
     * 需要给案场人员发送信息，已处理
     * @param agencyAccessToken
     * @param assistantAccessToken
     * @param companyUuid
     * @param domain
     * @param cusPreId
     * @param premisesId
     * @param staffId
     * @param cusName
     * @param cusPhone
     */
    @Override
    @Async
    public void sendSubscribeSuccessTemplateMsg(String agencyAccessToken, String assistantAccessToken, String companyUuid
            , String domain, Long cusPreId, String premisesId, String staffId, String cusName, String cusPhone) {
        if (StringUtils.isBlank(assistantAccessToken) && StringUtils.isBlank(agencyAccessToken)) {
            logger.info("sendSubscribeSuccessTemplateMsg ---- assistantAccessToken且agencyAccessToken为空，不发送模板消息");
            return;
        }
        if (StringUtils.isBlank(premisesId)) {
            logger.info("sendSubscribeSuccessTemplateMsg ---- 楼盘ID不能为空！");
            return;
        }
        if (StringUtils.isBlank(companyUuid) && StringUtils.isBlank(domain)) {
            logger.info("sendSubscribeSuccessTemplateMsg ---- companyUuid和domain不能同时为空！");
            return;
        }
        if (StringUtils.isBlank(staffId)) {
            logger.info("sendSubscribeSuccessTemplateMsg ---- 经纪人ID不能为空！");
            return;
        }
        // 判断权限
//        boolean flag = wxmsgModelService.checkWeixinModelSet(null,companyUuid,domain,WxMessageTemplate.SUBSCRIBE_SUCCESS_TEMPLATE_ID);
//        if(!flag){
//            logger.info("sendSubscribeSuccessTemplateMsg ---- 发送微信模板消息失败：发送认购成功模板开关未打开");
//            return;
//        }
        //获取经纪人openId
        PartnerInfoDto partnerInfoDto = new PartnerInfoDto();
        partnerInfoDto.setId(Long.valueOf(staffId));
        partnerInfoDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
        partnerInfoDto.setStatus(PartnerStatusEnum.VALID.getNo());
        PartnerInfo agentPi = partnerInfoService.selectByDto(partnerInfoDto);
        //获取接收微信模板消息驻场人员openid
        CaseMemberDto caseMemberDto = new CaseMemberDto();
        caseMemberDto.setPremisesId(Long.valueOf(premisesId));
        List<PartnerInfo> partnerInfoList = caseMemberService.selectListForWxMsg(caseMemberDto);
        // 筛选出有权限的用户
        partnerInfoList = filterPartnerByPermission(partnerInfoList, agentPi);
        List<String> assignOpenIdList = null;
        if(partnerInfoList != null && partnerInfoList.size() > 0) {
            assignOpenIdList = partnerInfoList.stream().filter(partnerInfo -> partnerInfo.getWxOpenid() != null).map(PartnerInfo::getWxOpenid).collect(Collectors.toList());
        }
        if (assignOpenIdList == null) {
            logger.info("sendSubscribeSuccessTemplateMsg ---- 获取驻场人员openId失败或者数据为空！");
            return;
        }
        List<String> hideWxOpenIds = getHideWxOpenIds(assignOpenIdList);
        //组装数据
        Map<String, List<String>> openIdMap = new HashMap<>();
        List<String> openIdList = new ArrayList<>();
        openIdList.add(agentPi != null ? agentPi.getWxOpenid() : "");
        List<PartnerInfo> reveivePartnerInfos = new ArrayList<>();
        reveivePartnerInfos.add(agentPi);
        if(CollectionUtils.isNotEmpty(partnerInfoList)) {
            reveivePartnerInfos.addAll(partnerInfoList);
        }
        openIdMap.put(AGENCY_SYSTEM, openIdList);
        openIdMap.put(ASSISTANT_SYSTEM, assignOpenIdList);

        //楼盘信息
        PremisesDto premisesDto = new PremisesDto();
        premisesDto.setId(Long.valueOf(premisesId));
        List<Premises> premisesList = premisesService.selectIdListByDto(premisesDto);
        if (premisesList == null || premisesList.size() == 0) {
            logger.info("sendSubscribeSuccessTemplateMsg ---- 未获取到楼盘信息！");
            return;
        }
        Premises premises = premisesList.get(0);
        //获取商户名称
        Company company = companyService.selectById(premises.getCompanyId());
        if (null == company) {
            logger.info("sendSubscribeSuccessTemplateMsg ---- 未获取到获取商户名称！");
            return;
        }
        //add by zilong.liu update for 分销小程序消息
        String modelSystemId = SystemIdEnum.AGENCY_h5.getCode();
        if (agentPi != null) {
        	agencyAccessToken = wxAccessTokenCacheUtils.getAccessTokenIfWeappMsg(company, agentPi.getLastLoginSystemId(), agencyAccessToken);
        	// 原固定使用分销助手的模板，现如果登录是分校小程序，需要使用小程序对应公众号配置的对应模板
        	modelSystemId = (SystemIdEnum.WEAPP_AGENCY.getCode().equals(agentPi.getLastLoginSystemId()) 
        			&& "1".equals(company.getEnableWeappMsg()))? 
        					SystemIdEnum.WEAPP_AGENCY_WX_ACCOUNTS.getCode(): SystemIdEnum.AGENCY_h5.getCode();
        }
		//add by zilong.liu update for 分销小程序消息
        
        companyUuid = company.getCompanyUuid();
        //获取微信模板配置失败
        Map<Integer,WxmsgModel> agencyWxMap = subscriptionApiService.getSubscriptionModelMsg(companyUuid
                , domain,modelSystemId);
        if(agencyWxMap == null || agencyWxMap.size() == 0) {
        	logger.info("agencyWxMap is null, 请检查运营后台配置");
        	return;
        }
        Map<Integer, WxmsgModel> assistantWxMap = subscriptionApiService.getSubscriptionModelMsg(companyUuid
                , domain, SystemIdEnum.ASSISTANT.getCode());
        if(assistantWxMap == null || assistantWxMap.size() == 0 || assistantWxMap.get(WxMessageTemplate.SUBSCRIBE_SUCCESS_TEMPLATE_ID) == null) {
        	openIdMap.remove(ASSISTANT_SYSTEM);
        }

        for (String systemType : openIdMap.keySet()) {
            //agencyAccessToken 或 assistantAccessToken 为空说明获取失败或者未开通发送模板消息
            if((systemType.equals(AGENCY_SYSTEM) && StringUtils.isBlank(agencyAccessToken))
                    || (systemType.equals(ASSISTANT_SYSTEM) && StringUtils.isBlank(assistantAccessToken))) {
                logger.info("sendSubscribeSuccessTemplateMsg ---- assistantAccessToken或agencyAccessToken为空！");
                continue;
            }
            List<String> openIdTempList = openIdMap.get(systemType);
            if(CollectionUtils.isEmpty(openIdTempList)){
                return;
            }
            for (String openId : openIdTempList) {
                try {
                    TreeMap<String, HashMap<String, String>> params = new TreeMap<>();
                    params.put("first", WechatTemplateMsg.item("恭喜认购成功！", "#000000"));
                    String realPhone = getRealPhoneByCaseMemberAuth(hideWxOpenIds, cusPhone, openId, systemType, Long.valueOf(premisesId));
                    params.put("keyword1", WechatTemplateMsg.item(cusName + " " + realPhone));
                    params.put("keyword2", WechatTemplateMsg.item(premises.getName()));
                    params.put("keyword3", WechatTemplateMsg.item("认购成功"));
                    params.put("keyword4", WechatTemplateMsg.item(company.getCompanyName()));
                    params.put("remark", WechatTemplateMsg.item("请及时跟进后续业务"));
                    WechatTemplateMsg wechatTemplateMsg = new WechatTemplateMsg();
                    String templateId = null;
                    String url = null;
                    if (systemType.equals(AGENCY_SYSTEM) && !agencyWxMap.isEmpty()) {
                        templateId = agencyWxMap.get(WxMessageTemplate.SUBSCRIBE_SUCCESS_TEMPLATE_ID).getWxModelmsgId();
                        url = h5UrlConfig.getWxTemplateMsgAgencyUrl() + agencyCusPreDetailUrl;
                        //add by zilong.liu 最后登录分销小程序跳转至小程序
                        url = url.replace(COMPANY_UUID, companyUuid).replace(CUS_PRE_ID, cusPreId.toString());
						wechatTemplateMsg.setUrl(url);
						if(agentPi != null && company != null) {
							addMiniProgram(agentPi.getLastLoginSystemId(), companyUuid, company.getEnableWeappMsg(), wechatTemplateMsg, cusPreId);
						}
                        //add by zilong.liu 最后登录分销小程序跳转至小程序
                    } else {
                        templateId = assistantWxMap.get(WxMessageTemplate.SUBSCRIBE_SUCCESS_TEMPLATE_ID).getWxModelmsgId();
                        url = h5UrlConfig.getWxTemplateMsgAssistantUrl() + assistantCusPreDetailUrl;
                        url = url.replace(COMPANY_UUID, companyUuid).replace(CUS_PRE_ID, cusPreId.toString());
                        wechatTemplateMsg.setUrl(url);
                    }
                    wechatTemplateMsg.setTemplate_id(templateId);
                    wechatTemplateMsg.setTouser(openId);
                    wechatTemplateMsg.setData(params);
                    String data = JSON.toJSONString(wechatTemplateMsg);
                    TemplateMessageResult result = wechatTemplateMessageService.sendTemplate(systemType.equals(AGENCY_SYSTEM)?agencyAccessToken:assistantAccessToken, data);

                    // update by zilong.liu  分销小程序渠道变更
                    String systemId = modelSystemId;
                    if(systemType.equals(ASSISTANT_SYSTEM)) {
                    	systemId = SystemIdEnum.ASSISTANT.getCode();
                    }
//                    String systemId = systemType.equals(AGENCY_SYSTEM)?SystemIdEnum.AGENCY_h5.getCode(): SystemIdEnum.ASSISTANT.getCode();
                    // update by zilong.liu  分销小程序渠道变更
                    
                    String receiveOpenId = openId;
                    String modelType = String.valueOf(WxMessageTemplate.SUBSCRIBE_SUCCESS_TEMPLATE_ID);
                    String modelUuid = templateId;
                    buildWXFailureMsg(getPartnerId(reveivePartnerInfos, receiveOpenId), companyUuid, systemId, receiveOpenId, data, modelType, modelUuid, result, cusPreId);

                    Thread.sleep(1000L);
                } catch (InterruptedException ie) {
                    logger.error("sendSubscribeSuccessTemplateMsg InterruptedException---- 发送微信模板消息失败：{}", ie);
                } catch (Exception e) {
                    logger.error("sendSubscribeSuccessTemplateMsg ---- 发送微信模板消息失败：{}", e);
                }
            }
        }
    }

    /**
     * 发送交易失败微信模板提醒
     * 需要给案场人员发送消息，已处理
     * @param agencyAccessToken
     * @param assistantAccessToken
     * @param wxMsgCommonDto
     * @param cusPreId
     * @param premisesId
     * @param staffId
     * @param cusName
     * @param cusPhone
     * @param failRemark
     */
    @Override
    @Async
    public void sendDealFailTemplateMsg(String agencyAccessToken, String assistantAccessToken, WxMsgCommonDto wxMsgCommonDto, Long cusPreId, String premisesId, String staffId, String cusName, String cusPhone, String failRemark) {
        if (StringUtils.isBlank(assistantAccessToken) && StringUtils.isBlank(agencyAccessToken)) {
            logger.info("sendDealFailTemplateMsg ---- assistantAccessToken且agencyAccessToken为空，不发送模板消息");
            return;
        }
        if (StringUtils.isBlank(premisesId)) {
            logger.info("sendDealFailTemplateMsg ---- 楼盘ID不能为空！");
            return;
        }
        if (StringUtils.isBlank(wxMsgCommonDto.getCompanyUuid()) && StringUtils.isBlank(wxMsgCommonDto.getDomain())) {
            logger.info("sendDealFailTemplateMsg ---- companyUuid和domain不能同时为空！");
            return;
        }
        if (StringUtils.isBlank(staffId)) {
            logger.info("sendDealFailTemplateMsg ---- 经纪人ID不能为空！");
            return;
        }
        String companyUuid = wxMsgCommonDto.getCompanyUuid();
        String domain = wxMsgCommonDto.getDomain();
        // 判断权限
//        boolean flag = wxmsgModelService.checkWeixinModelSet(null,companyUuid,domain,WxMessageTemplate.DEAL_FAIL_TEMPLATE_ID);
//        if(!flag){
//            logger.info("sendVisitSuccessTemplateMsg ---- 发送微信模板消息失败：发送交易失败模板开关未打开");
//            return;
//        }
        //获取经纪人openId
        PartnerInfoDto partnerInfoDto = new PartnerInfoDto();
        partnerInfoDto.setId(Long.valueOf(staffId));
        partnerInfoDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
        partnerInfoDto.setStatus(PartnerStatusEnum.VALID.getNo());
        PartnerInfo agentPi = partnerInfoService.selectByDto(partnerInfoDto);
        //获取接收微信模板消息驻场人员openid
        CaseMemberDto caseMemberDto = new CaseMemberDto();
        caseMemberDto.setPremisesId(Long.valueOf(premisesId));
        List<PartnerInfo> partnerInfoList = caseMemberService.selectListForWxMsg(caseMemberDto);
        // 筛选出有权限的用户
        partnerInfoList = filterPartnerByPermission(partnerInfoList, agentPi);
        List<String> assignOpenIdList = null;
        if(partnerInfoList != null && partnerInfoList.size() > 0) {
            assignOpenIdList = partnerInfoList.stream().filter(partnerInfo -> partnerInfo.getWxOpenid() != null).map(PartnerInfo::getWxOpenid).collect(Collectors.toList());
        }
        if (assignOpenIdList == null) {
            logger.info("sendVisitSuccessTemplateMsg ---- 获取驻场人员openId失败或者数据为空！");
            return;
        }
        List<String> hideWxOpenIds = getHideWxOpenIds(assignOpenIdList);
        //组装数据
        Map<String, List<String>> openIdMap = new HashMap<>();
        List<String> openIdList = new ArrayList<>();
        openIdList.add(agentPi != null ? agentPi.getWxOpenid() : "");
        List<PartnerInfo> reveivePartnerInfos = new ArrayList<>();
        reveivePartnerInfos.add(agentPi);
        if(CollectionUtils.isNotEmpty(partnerInfoList)) {
            reveivePartnerInfos.addAll(partnerInfoList);
        }
        openIdMap.put(AGENCY_SYSTEM, openIdList);
        openIdMap.put(ASSISTANT_SYSTEM, assignOpenIdList);

        //楼盘信息
        PremisesDto premisesDto = new PremisesDto();
        premisesDto.setId(Long.valueOf(premisesId));
        List<Premises> premisesList = premisesService.selectIdListByDto(premisesDto);
        if (premisesList == null || premisesList.size() == 0) {
            logger.info("sendDealFailTemplateMsg ---- 未获取到楼盘信息！");
            return;
        }
        Premises premises = premisesList.get(0);
        //获取商户名称
        Company company = companyService.selectById(premises.getCompanyId());
        if (null == company) {
            logger.info("sendDealFailTemplateMsg ---- 未获取到获取商户名称！");
            return;
        }
        
        //add by zilong.liu update for 分销小程序消息
        String modelSystemId = SystemIdEnum.AGENCY_h5.getCode();
        if (agentPi != null) {
        	agencyAccessToken = wxAccessTokenCacheUtils.getAccessTokenIfWeappMsg(company, agentPi.getLastLoginSystemId(), agencyAccessToken);
        	// 原固定使用分销助手的模板，现如果登录是分校小程序，需要使用小程序对应公众号配置的对应模板
        	modelSystemId = (SystemIdEnum.WEAPP_AGENCY.getCode().equals(agentPi.getLastLoginSystemId()) 
        			&& "1".equals(company.getEnableWeappMsg()))? 
        					SystemIdEnum.WEAPP_AGENCY_WX_ACCOUNTS.getCode(): SystemIdEnum.AGENCY_h5.getCode();
        }
		//add by zilong.liu update for 分销小程序消息
                		
        companyUuid = company.getCompanyUuid();
        //获取微信模板配置失败
        Map<Integer,WxmsgModel> agencyWxMap = subscriptionApiService.getSubscriptionModelMsg(companyUuid
                , domain,modelSystemId);
        if(agencyWxMap == null || agencyWxMap.size() == 0) {
        	logger.info("agencyWxMap is null, 请检查运营后台配置: companyUuid{}", companyUuid);
        	return;
        }
        Map<Integer, WxmsgModel> assistantWxMap = subscriptionApiService.getSubscriptionModelMsg(companyUuid
                , domain, SystemIdEnum.ASSISTANT.getCode());
//        if (assistantWxMap == null && agencyWxMap == null) {
//            logger.info("sendDealFailTemplateMsg ---- 获取微信模板配置失败！");
//            return;
//        }
        if(assistantWxMap == null || assistantWxMap.size() == 0 || assistantWxMap.get(WxMessageTemplate.DEAL_FAIL_TEMPLATE_ID) == null) {
        	openIdMap.remove(ASSISTANT_SYSTEM);
        }
        for (String systemType : openIdMap.keySet()) {
            //agencyAccessToken 或 assistantAccessToken 为空说明获取失败或者未开通发送模板消息
            if((systemType.equals(AGENCY_SYSTEM) && StringUtils.isBlank(agencyAccessToken))
                    || (systemType.equals(ASSISTANT_SYSTEM) && StringUtils.isBlank(assistantAccessToken))) {
                logger.info("sendDealFailTemplateMsg ---- assistantAccessToken或agencyAccessToken为空！");
                continue;
            }
            List<String> openIdTempList = openIdMap.get(systemType);
            if(CollectionUtils.isEmpty(openIdTempList)){
                return;
            }
            for (String openId : openIdTempList) {
                try {
                    TreeMap<String, HashMap<String, String>> params = new TreeMap<>();
                    params.put("first", WechatTemplateMsg.item("有一条报备交易失败", "#000000"));
                    String realPhone = getRealPhoneByCaseMemberAuth(hideWxOpenIds, cusPhone, openId, systemType, Long.valueOf(premisesId));
                    params.put("keyword1", WechatTemplateMsg.item(cusName + " " + realPhone));
                    params.put("keyword2", WechatTemplateMsg.item(premises.getName()));
                    params.put("keyword3", WechatTemplateMsg.item("交易失败"));
                    params.put("keyword4", WechatTemplateMsg.item(company.getCompanyName()));
                    params.put("remark", WechatTemplateMsg.item("失败原因：" + (StringUtils.isNotBlank(failRemark) ? failRemark : "")));
                    WechatTemplateMsg wechatTemplateMsg = new WechatTemplateMsg();
                    String templateId = null;
                    String url = null;
                    if (systemType.equals(AGENCY_SYSTEM) && !agencyWxMap.isEmpty()) {
                        templateId = agencyWxMap.get(WxMessageTemplate.DEAL_FAIL_TEMPLATE_ID).getWxModelmsgId();
                        url = h5UrlConfig.getWxTemplateMsgAgencyUrl() + agencyCusPreDetailUrl;
                        //add by zilong.liu 最后登录分销小程序跳转至小程序
                        url = url.replace(COMPANY_UUID, companyUuid).replace(CUS_PRE_ID, cusPreId.toString());
						wechatTemplateMsg.setUrl(url);
						if(agentPi != null && company != null) {
							addMiniProgram(agentPi.getLastLoginSystemId(), companyUuid, company.getEnableWeappMsg(), wechatTemplateMsg, cusPreId);
						}
                        //add by zilong.liu 最后登录分销小程序跳转至小程序
                    } else {
                        templateId = assistantWxMap.get(WxMessageTemplate.DEAL_FAIL_TEMPLATE_ID).getWxModelmsgId();
                        url = h5UrlConfig.getWxTemplateMsgAssistantUrl() + assistantCusPreDetailUrl;
                        url = url.replace(COMPANY_UUID, companyUuid).replace(CUS_PRE_ID, cusPreId.toString());
                        wechatTemplateMsg.setUrl(url);
                    }
                    wechatTemplateMsg.setTemplate_id(templateId);
                    wechatTemplateMsg.setTouser(openId);
                    wechatTemplateMsg.setData(params);
                    String data = JSON.toJSONString(wechatTemplateMsg);
                    TemplateMessageResult result = wechatTemplateMessageService.sendTemplate(systemType.equals(AGENCY_SYSTEM)?agencyAccessToken:assistantAccessToken, data);

                    // update by zilong.liu  分销小程序渠道变更
                    String systemId = modelSystemId;
                    if(systemType.equals(ASSISTANT_SYSTEM)) {
                    	systemId = SystemIdEnum.ASSISTANT.getCode();
                    }
//                    String systemId = systemType.equals(AGENCY_SYSTEM)?SystemIdEnum.AGENCY_h5.getCode(): SystemIdEnum.ASSISTANT.getCode();
                    // update by zilong.liu  分销小程序渠道变更
                    
                    String receiveOpenId = openId;
                    String modelType = String.valueOf(WxMessageTemplate.DEAL_FAIL_TEMPLATE_ID);
                    String modelUuid = templateId;
                    buildWXFailureMsg(getPartnerId(reveivePartnerInfos, receiveOpenId), companyUuid, systemId, receiveOpenId, data, modelType, modelUuid, result, cusPreId);

                    Thread.sleep(1000L);
                } catch (InterruptedException ie) {
                    logger.error("sendDealFailTemplateMsg InterruptedException---- 发送微信模板消息失败：{}", ie);
                } catch (Exception e) {
                    logger.error("sendDealFailTemplateMsg ---- 发送微信模板消息失败：{}", e);
                }
            }
        }
    }

    /**
     * 发送楼盘上架微信模板提醒
     * 向经纪人发送，切无手机号
     * @param agencyAccessToken
     * @param companyUuid
     * @param domain
     * @param premisesId
     */
    @Override
    @Async
    public void sendPremisesShelveTemplateMsg(String agencyAccessToken, String companyUuid, String domain, String premisesId) {
        // TODO 每5S推一条，推不动。暂时关闭
        if(true) {
            return;
        }
        if (StringUtils.isBlank(agencyAccessToken)) {
            logger.info("sendPremisesShelveTemplateMsg ---- agencyAccessToken，不发送模板消息");
            return;
        }
        if (StringUtils.isBlank(premisesId)) {
            logger.info("sendPremisesShelveTemplateMsg ---- 楼盘ID不能为空！");
            return;
        }
        if (StringUtils.isBlank(companyUuid) && StringUtils.isBlank(domain)) {
            logger.info("sendPremisesShelveTemplateMsg ---- companyUuid和domain不能同时为空！");
            return;
        }
        // 判断权限
//        boolean flag = wxmsgModelService.checkWeixinModelSet(null,companyUuid,domain,WxMessageTemplate.PREMISES_SHELVE_TEMPLATE_ID);
//        if(!flag){
//            logger.info("sendPremisesShelveTemplateMsg ---- 发送微信模板消息失败：发送楼盘上架模板开关未打开");
//            return;
//        }
        //获取楼盘指定分销机构的所有经纪人openid
        List<String> openIdList = partnerInfoService.selectOpenIdByAssign(Long.valueOf(premisesId));
        if (openIdList == null || openIdList.size() == 0) {
            logger.info("sendPremisesShelveTemplateMsg ---- 获取经纪人openId失败或者数据为空！");
            return;
        }

        //楼盘信息
        PremisesDto premisesDto = new PremisesDto();
        premisesDto.setId(Long.valueOf(premisesId));
        List<Premises> premisesList = premisesService.selectIdListByDto(premisesDto);
        if (premisesList == null || premisesList.size() == 0) {
            logger.info("sendPremisesShelveTemplateMsg ---- 未获取到楼盘信息！");
            return;
        }
        Premises premises = premisesList.get(0);
        //获取商户名称
        Company company = companyService.selectById(premises.getCompanyId());
        if (null == company) {
            logger.info("sendPremisesShelveTemplateMsg ---- 未获取到获取商户名称！");
            return;
        }
        companyUuid = company.getCompanyUuid();
        //获取微信模板配置失败
        Map<Integer, WxmsgModel> assistantWxMap = subscriptionApiService.getSubscriptionModelMsg(companyUuid
                , domain, SystemIdEnum.ASSISTANT.getCode());
        if (assistantWxMap == null) {
            logger.info("sendPremisesShelveTemplateMsg ---- 获取微信模板配置失败！");
            return;
        }
        for (String openId : openIdList) {
            try {
                TreeMap<String, HashMap<String, String>> params = new TreeMap<>();
                params.put("first", WechatTemplateMsg.item("新项目上架", "#000000"));
                params.put("keyword1", WechatTemplateMsg.item(premises.getName()));
                params.put("keyword2", WechatTemplateMsg.item("已上架"));
                params.put("remark", WechatTemplateMsg.item("赶快来查看楼盘详情，报备客户吧"));
                WechatTemplateMsg wechatTemplateMsg = new WechatTemplateMsg();
                wechatTemplateMsg.setTemplate_id(assistantWxMap.get(WxMessageTemplate.PREMISES_SHELVE_TEMPLATE_ID).getWxModelmsgId());
                wechatTemplateMsg.setTouser(openId);
                wechatTemplateMsg.setData(params);
                String data = JSON.toJSONString(wechatTemplateMsg);
                TemplateMessageResult result = wechatTemplateMessageService.sendTemplate(agencyAccessToken, data);

                String systemId = SystemIdEnum.ASSISTANT.getCode();
                String receiveOpenId = openId;
                String modelType = String.valueOf(WxMessageTemplate.PREMISES_SHELVE_TEMPLATE_ID);
                String modelUuid = assistantWxMap.get(WxMessageTemplate.PREMISES_SHELVE_TEMPLATE_ID).getWxModelmsgId();
                // 0L 只是为了避免报错，没有添加构建时记录partnerId的逻辑
                buildWXFailureMsg(0L, companyUuid, systemId, receiveOpenId, data, modelType, modelUuid, result, Long.valueOf(premisesId));

                Thread.sleep(1000L);
            } catch (InterruptedException ie) {
                logger.error("sendPremisesShelveTemplateMsg InterruptedException---- 发送微信模板消息失败：{}", ie);
            } catch (Exception e) {
                logger.error("sendPremisesShelveTemplateMsg ---- 发送微信模板消息失败：{}", e);
            }
        }
    }

    /**
     * 发送楼盘下架微信模板提醒(设置销售状态)
     * 向经纪人发送，且无手机号
     * @param agencyAccessToken
     * @param companyUuid
     * @param domain
     * @param premisesId
     * @param saleStatus
     */
    @Override
    @Async
    public void sendPremisesUnshelveTemplateMsg(String agencyAccessToken, String companyUuid, String domain, String premisesId, String saleStatus) {
        // TODO 每5S推一条，推不动。暂时关闭
        if(true) {
            return;
        }

        if (StringUtils.isBlank(agencyAccessToken)) {
            logger.info("sendPremisesUnshelveTemplateMsg ---- agencyAccessToken，不发送模板消息");
            return;
        }
        if (StringUtils.isBlank(premisesId)) {
            logger.info("sendPremisesUnshelveTemplateMsg ---- 楼盘ID不能为空！");
            return;
        }
        if (StringUtils.isBlank(companyUuid) && StringUtils.isBlank(domain)) {
            logger.info("sendPremisesUnshelveTemplateMsg ---- companyUuid和domain不能同时为空！");
            return;
        }
//        // 判断权限
//        boolean flag = wxmsgModelService.checkWeixinModelSet(null,companyUuid,domain,WxMessageTemplate.PREMISES_UNSHELVE_TEMPLATE_ID);
//        if(!flag){
//            logger.info("sendPremisesUnshelveTemplateMsg ---- 发送微信模板消息失败：发送楼盘下架模板开关未打开");
//            return;
//        }
        //获取楼盘指定分销机构的所有经纪人openid
        List<String> openIdList = partnerInfoService.selectOpenIdByAssign(Long.valueOf(premisesId));
        if (openIdList == null || openIdList.size() == 0) {
            logger.info("sendPremisesUnshelveTemplateMsg ---- 获取经纪人openId失败或者数据为空！");
            return;
        }
        //楼盘信息
        PremisesDto premisesDto = new PremisesDto();
        premisesDto.setId(Long.valueOf(premisesId));
        List<Premises> premisesList = premisesService.selectIdListByDto(premisesDto);
        if (premisesList == null || premisesList.size() == 0) {
            logger.info("sendPremisesUnshelveTemplateMsg ---- 未获取到楼盘信息！");
            return;
        }
        Premises premises = premisesList.get(0);
        //获取商户名称
        Company company = companyService.selectById(premises.getCompanyId());
        if (null == company) {
            logger.info("sendPremisesUnshelveTemplateMsg ---- 未获取到获取商户名称！");
            return;
        }
        companyUuid = company.getCompanyUuid();
        //获取微信模板配置失败
        Map<Integer, WxmsgModel> assistantWxMap = subscriptionApiService.getSubscriptionModelMsg(companyUuid
                , domain, SystemIdEnum.ASSISTANT.getCode());
        if (assistantWxMap == null) {
            logger.info("sendPremisesUnshelveTemplateMsg ---- 获取微信模板配置失败！");
            return;
        }
        for (String openId : openIdList) {
            try {
                TreeMap<String, HashMap<String, String>> params = new TreeMap<>();
                params.put("first", WechatTemplateMsg.item("项目已" + saleStatus, "#000000"));
                params.put("keyword1", WechatTemplateMsg.item(premises.getName()));
                params.put("keyword2", WechatTemplateMsg.item(saleStatus));
                params.put("remark", WechatTemplateMsg.item("现已无法再进行报备，历史报备不会受到影响"));
                WechatTemplateMsg wechatTemplateMsg = new WechatTemplateMsg();
                wechatTemplateMsg.setTemplate_id(assistantWxMap.get(WxMessageTemplate.PREMISES_UNSHELVE_TEMPLATE_ID).getWxModelmsgId());
                wechatTemplateMsg.setTouser(openId);
                wechatTemplateMsg.setData(params);
                String data = JSON.toJSONString(wechatTemplateMsg);
                TemplateMessageResult result = wechatTemplateMessageService.sendTemplate(agencyAccessToken, data);
                String systemId = SystemIdEnum.AGENCY_h5.getCode();
                String receiveOpenId = openId;
                String modelType = String.valueOf(WxMessageTemplate.PREMISES_UNSHELVE_TEMPLATE_ID);
                String modelUuid = assistantWxMap.get(WxMessageTemplate.PREMISES_UNSHELVE_TEMPLATE_ID).getWxModelmsgId();
                // 0L 只是为了避免报错，没有添加构建时记录partnerId的逻辑
                buildWXFailureMsg(0L, companyUuid, systemId, receiveOpenId, data, modelType, modelUuid, result, Long.valueOf(premisesId));
                Thread.sleep(1000L);
            } catch (InterruptedException ie) {
                logger.error("sendPremisesUnshelveTemplateMsg InterruptedException---- 发送微信模板消息失败：{}", ie);
            } catch (Exception e) {
                logger.error("sendPremisesUnshelveTemplateMsg ---- 发送微信模板消息失败：{}", e);
            }
        }
    }

    /**
     * 指定分销商之后需要处理的人员
     * 向经纪人发送，且无手机号
     * @param agencyAccessToken
     * @param companyUuid
     * @param domain
     * @param premisesId
     * @param cancelAgency
     * @param confirmAgency
     */
    @Async
    public void sendPremisesUnshelveTemplateMsgForAgency(String agencyAccessToken, String companyUuid, String domain, String premisesId, List<String> cancelAgency,List<String> confirmAgency){
        // TODO 每5S推一条，推不动。暂时关闭
        if(true) {
            return;
        }

        if (StringUtils.isBlank(agencyAccessToken)) {
            logger.info("sendPremisesUnshelveTemplateMsgForAgency ---- agencyAccessToken，不发送模板消息");
            return;
        }
        if (StringUtils.isBlank(premisesId)) {
            logger.info("sendPremisesUnshelveTemplateMsgForAgency ---- 楼盘ID不能为空！");
            return;
        }
        if (StringUtils.isBlank(companyUuid) && StringUtils.isBlank(domain)) {
            logger.info("sendPremisesUnshelveTemplateMsgForAgency ---- companyUuid和domain不能同时为空！");
            return;
        }
        //楼盘信息
        PremisesDto premisesDto = new PremisesDto();
        premisesDto.setId(Long.valueOf(premisesId));
        List<Premises> premisesList = premisesService.selectIdListByDto(premisesDto);
        if (premisesList == null || premisesList.size() == 0) {
            logger.info("sendPremisesUnshelveTemplateMsgForAgency ---- 未获取到楼盘信息！");
            return;
        }
        Premises premises = premisesList.get(0);
        //获取商户名称
        Company company = companyService.selectById(premises.getCompanyId());
        if (null == company) {
            logger.info("sendPremisesUnshelveTemplateMsgForAgency ---- 未获取到获取商户名称！");
            return;
        }
        companyUuid = company.getCompanyUuid();
        //获取微信模板配置失败
        Map<Integer, WxmsgModel> assistantWxMap = subscriptionApiService.getSubscriptionModelMsg(companyUuid
                , domain, SystemIdEnum.ASSISTANT.getCode());
        if (assistantWxMap == null) {
            logger.info("sendPremisesUnshelveTemplateMsgForAgency ---- 获取微信模板配置失败！");
            return;
        }
        //取消分销商的用户发送下架消息
        // 判断权限
//        boolean cancelFlag = wxmsgModelService.checkWeixinModelSet(null,companyUuid,domain,WxMessageTemplate.PREMISES_UNSHELVE_TEMPLATE_ID);
        List<String> cancelPartners = partnerInfoService.getPartnersByCompanyIds(cancelAgency);
//        if(cancelFlag) {
        for (String openId : cancelPartners) {
            try {
            	TreeMap<String, HashMap<String, String>> params = new TreeMap<>();
                params.put("first", WechatTemplateMsg.item("项目已下架", "#000000"));
                params.put("keyword1", WechatTemplateMsg.item(premises.getName()));
                params.put("keyword2", WechatTemplateMsg.item("下架"));
                params.put("remark", WechatTemplateMsg.item("现已无法再进行报备，历史报备不会受到影响"));
                WechatTemplateMsg wechatTemplateMsg = new WechatTemplateMsg();
                wechatTemplateMsg.setTemplate_id(assistantWxMap.get(WxMessageTemplate.PREMISES_UNSHELVE_TEMPLATE_ID).getWxModelmsgId());
                wechatTemplateMsg.setTouser(openId);
                wechatTemplateMsg.setData(params);
                String data = JSON.toJSONString(wechatTemplateMsg);
                TemplateMessageResult result = wechatTemplateMessageService.sendTemplate(agencyAccessToken, data);
                String systemId = SystemIdEnum.AGENCY_h5.getCode();
                String receiveOpenId = openId;
                String modelType = String.valueOf(WxMessageTemplate.PREMISES_UNSHELVE_TEMPLATE_ID);
                String modelUuid = assistantWxMap.get(WxMessageTemplate.PREMISES_UNSHELVE_TEMPLATE_ID).getWxModelmsgId();
                // 0L 只是为了避免报错，没有添加构建时记录partnerId的逻辑
                buildWXFailureMsg(0L, companyUuid, systemId, receiveOpenId, data, modelType, modelUuid, result, Long.valueOf(premisesId));
                Thread.sleep(1000L);
             } catch (InterruptedException ie) {
                 logger.error("sendPremisesUnshelveTemplateMsgForAgency InterruptedException---- 发送微信模板消息失败：{}", ie);
             } catch (Exception e) {
                 logger.error("sendPremisesUnshelveTemplateMsgForAgency ---- 发送微信模板消息失败：{}", e);
             }
         }
//         }
        //新指定分销商的用户发送上架消息
        List<String> confrimPartner =  partnerInfoService.getPartnersByCompanyIds(confirmAgency);
        // 判断权限
//        boolean confrimFlag = wxmsgModelService.checkWeixinModelSet(null,companyUuid,domain,WxMessageTemplate.PREMISES_SHELVE_TEMPLATE_ID);
//        if(confrimFlag) {
        for (String openId : confrimPartner) {
            try {
                TreeMap<String, HashMap<String, String>> params = new TreeMap<>();
                params.put("first", WechatTemplateMsg.item("项目已上架", "#000000"));
                params.put("keyword1", WechatTemplateMsg.item(premises.getName()));
                params.put("keyword2", WechatTemplateMsg.item("上架"));
                params.put("remark", WechatTemplateMsg.item("赶快来查看楼盘详情、报备客户吧"));
                WechatTemplateMsg wechatTemplateMsg = new WechatTemplateMsg();
                wechatTemplateMsg.setTemplate_id(assistantWxMap.get(WxMessageTemplate.PREMISES_SHELVE_TEMPLATE_ID).getWxModelmsgId());
                wechatTemplateMsg.setTouser(openId);
                wechatTemplateMsg.setData(params);
                String data = JSON.toJSONString(wechatTemplateMsg);
                TemplateMessageResult result = wechatTemplateMessageService.sendTemplate(agencyAccessToken, data);

                String systemId = SystemIdEnum.AGENCY_h5.getCode();
                String receiveOpenId = openId;
                String modelType = String.valueOf(WxMessageTemplate.PREMISES_SHELVE_TEMPLATE_ID);
                String modelUuid = assistantWxMap.get(WxMessageTemplate.PREMISES_SHELVE_TEMPLATE_ID).getWxModelmsgId();
                // 0L 只是为了避免报错，没有添加构建时记录partnerId的逻辑
                buildWXFailureMsg(0L, companyUuid, systemId, receiveOpenId, data, modelType, modelUuid, result, Long.valueOf(premisesId));

                Thread.sleep(1000L);
            } catch (InterruptedException ie) {
                logger.error("sendPremisesUnshelveTemplateMsgForAgency InterruptedException---- 发送微信模板消息失败：{}", ie);
            } catch (Exception e) {
                logger.error("sendPremisesUnshelveTemplateMsgForAgency ---- 发送微信模板消息失败：{}", e);
            }
        }
//        }
    }

    /**
     * 指定分销商之后发消息给每个管理员
     * 向经纪人发送，且无手机号
     * @param agencyAccessToken
     * @param companyUuid
     * @param domain
     * @param premisesId
     * @param cancelAgency
     * @param confirmAgency
     */
    @Async
    public void sendPremisesUnshelveTemplateMsgForAgencyAdmin(String agencyAccessToken, String companyUuid, String domain, String premisesId, List<String> cancelAgency,List<String> confirmAgency){
        // TODO 每5S推一条，推不动。暂时关闭
        if(true) {
            return;
        }

        if (StringUtils.isBlank(agencyAccessToken)) {
            logger.info("sendPremisesUnshelveTemplateMsgForAgencyAdmin ---- agencyAccessToken，不发送模板消息");
            return;
        }
        if (StringUtils.isBlank(premisesId)) {
            logger.info("sendPremisesUnshelveTemplateMsgForAgencyAdmin ---- 楼盘ID不能为空！");
            return;
        }
        if (StringUtils.isBlank(companyUuid) && StringUtils.isBlank(domain)) {
            logger.info("sendPremisesUnshelveTemplateMsgForAgencyAdmin ---- companyUuid和domain不能同时为空！");
            return;
        }
        //获取楼盘指定分销机构的所有经纪人openid
//        List<String> openIdList = partnerInfoService.selectOpenIdByAssign(Long.valueOf(premisesId));
//        if (openIdList == null || openIdList.size() == 0) {
//            logger.error("sendPremisesUnshelveTemplateMsgForAgency ---- 获取经纪人openId失败或者数据为空！");
//            return;
//        }
        //楼盘信息
        PremisesDto premisesDto = new PremisesDto();
        premisesDto.setId(Long.valueOf(premisesId));
        List<Premises> premisesList = premisesService.selectIdListByDto(premisesDto);
        if (premisesList == null || premisesList.size() == 0) {
            logger.info("sendPremisesUnshelveTemplateMsgForAgencyAdmin ---- 未获取到楼盘信息！");
            return;
        }
        Premises premises = premisesList.get(0);
        //获取商户名称
        Company company = companyService.selectById(premises.getCompanyId());
        if (null == company) {
            logger.info("sendPremisesUnshelveTemplateMsgForAgencyAdmin ---- 未获取到获取商户名称！");
            return;
        }
        companyUuid = company.getCompanyUuid();
        //获取微信模板配置失败
        Map<Integer, WxmsgModel> assistantWxMap = subscriptionApiService.getSubscriptionModelMsg(companyUuid
                , domain, SystemIdEnum.ASSISTANT.getCode());
        if (assistantWxMap == null) {
            logger.info("sendPremisesUnshelveTemplateMsgForAgencyAdmin ---- 获取微信模板配置失败！");
            return;
        }
        //取消分销商的用户发送下架消息
        // 判断权限
//        boolean cancelFlag = wxmsgModelService.checkWeixinModelSet(null,companyUuid,domain,WxMessageTemplate.PREMISES_UNSHELVE_TEMPLATE_ID);
        List<String> cancelPartners = partnerInfoService.getPartnersAdminByCompanyIds(cancelAgency);
//        if(cancelFlag) {
         for (String openId : cancelPartners) {
             try {
                 TreeMap<String, HashMap<String, String>> params = new TreeMap<>();
                 params.put("first", WechatTemplateMsg.item("项目已下架", "#000000"));
                 params.put("keyword1", WechatTemplateMsg.item(premises.getName()));
                 params.put("keyword2", WechatTemplateMsg.item("下架"));
                 params.put("remark", WechatTemplateMsg.item("现已无法再进行报备，历史报备不会受到影响"));
                 WechatTemplateMsg wechatTemplateMsg = new WechatTemplateMsg();
                 wechatTemplateMsg.setTemplate_id(assistantWxMap.get(WxMessageTemplate.PREMISES_UNSHELVE_TEMPLATE_ID).getWxModelmsgId());
                 wechatTemplateMsg.setTouser(openId);
                 wechatTemplateMsg.setData(params);
                 String data = JSON.toJSONString(wechatTemplateMsg);
                 TemplateMessageResult result = wechatTemplateMessageService.sendTemplate(agencyAccessToken, data);

                 String systemId = SystemIdEnum.AGENCY_h5.getCode();
                 String receiveOpenId = openId;
                 String modelType = String.valueOf(WxMessageTemplate.PREMISES_UNSHELVE_TEMPLATE_ID);
                 String modelUuid = assistantWxMap.get(WxMessageTemplate.PREMISES_UNSHELVE_TEMPLATE_ID).getWxModelmsgId();
                 //// 0L 只是为了避免报错，没有添加构建时记录partnerId的逻辑
                 buildWXFailureMsg(0L, companyUuid, systemId, receiveOpenId, data, modelType, modelUuid, result, Long.valueOf(premisesId));

                 Thread.sleep(1000L);
             } catch (InterruptedException ie) {
                 logger.error("sendPremisesUnshelveTemplateMsgForAgencyAdmin InterruptedException---- 发送微信模板消息失败：{}", ie);
             } catch (Exception e) {
                 logger.error("sendPremisesUnshelveTemplateMsgForAgencyAdmin ---- 发送微信模板消息失败：{}", e);
             }
         }
//         }
        //新指定分销商的用户发送上架消息
        List<String> confrimPartner =  partnerInfoService.getPartnersAdminByCompanyIds(confirmAgency);
        // 判断权限
//        boolean confrimFlag = wxmsgModelService.checkWeixinModelSet(null,companyUuid,domain,WxMessageTemplate.PREMISES_SHELVE_TEMPLATE_ID);
//        if(confrimFlag) {
        for (String openId : confrimPartner) {
            try {
                TreeMap<String, HashMap<String, String>> params = new TreeMap<>();
                params.put("first", WechatTemplateMsg.item("项目已上架", "#000000"));
                params.put("keyword1", WechatTemplateMsg.item(premises.getName()));
                params.put("keyword2", WechatTemplateMsg.item("上架"));
                params.put("remark", WechatTemplateMsg.item("赶快来查看楼盘详情、报备客户吧"));
                WechatTemplateMsg wechatTemplateMsg = new WechatTemplateMsg();
                wechatTemplateMsg.setTemplate_id(assistantWxMap.get(WxMessageTemplate.PREMISES_SHELVE_TEMPLATE_ID).getWxModelmsgId());
                wechatTemplateMsg.setTouser(openId);
                wechatTemplateMsg.setData(params);
                String data = JSON.toJSONString(wechatTemplateMsg);
                TemplateMessageResult result = wechatTemplateMessageService.sendTemplate(agencyAccessToken, data);

                String systemId = SystemIdEnum.AGENCY_h5.getCode();
                String receiveOpenId = openId;
                String modelType = String.valueOf(WxMessageTemplate.PREMISES_SHELVE_TEMPLATE_ID);
                String modelUuid = assistantWxMap.get(WxMessageTemplate.PREMISES_SHELVE_TEMPLATE_ID).getWxModelmsgId();
                // 0L 只是为了避免报错，没有添加构建时记录partnerId的逻辑
                buildWXFailureMsg(0L, companyUuid, systemId, receiveOpenId, data, modelType, modelUuid, result, Long.valueOf(premisesId));

                Thread.sleep(1000L);
            } catch (InterruptedException ie) {
                logger.error("sendPremisesUnshelveTemplateMsgForAgencyAdmin InterruptedException---- 发送微信模板消息失败：{}", ie);
            } catch (Exception e) {
                logger.error("sendPremisesUnshelveTemplateMsgForAgencyAdmin ---- 发送微信模板消息失败：{}", e);
            }
        }
//        }
    }

    @Async
    @Override
    public void sendFollowTemplateMsg(String assistantAccessToken, String companyUuid, Long reportId) {

        CustomerPremises customerPremises = customerPremisesService.selectById(reportId);
        if(Objects.isNull(customerPremises)){
            logger.error("sendFollowTemplateMsg error -- 报备不存在，不发送模板消息:{}", reportId);
            return;
        }
        String currentStatus = CustomerStatusEnum.getDescByNo(customerPremises.getCustomerStatus());
        Long premisesId = customerPremises.getPremisesId();
        Long staffId = customerPremises.getStaffId();
        String cusName = customerPremises.getName();
        String cusPhone = customerPremises.getMobile();
        if (StringUtils.isBlank(assistantAccessToken)
                || Objects.isNull(premisesId)
                || StringUtils.isBlank(companyUuid)
                || Objects.isNull(staffId)) {
            logger.error("sendFollowTemplateMsg error -- 必要参数校验不通过，不发送模板消息:{},{},{},{}",assistantAccessToken,premisesId,companyUuid,staffId);
            return;
        }

        //获取经纪人信息
        PartnerInfo agentPi = partnerInfoService.selectById(Long.valueOf(staffId));
        if(Objects.isNull(agentPi)) {
            logger.error("sendFollowTemplateMsg error -- 报备经纪人不存在，不发送模板消息: {}", staffId);
            return;
        }

        //获取接收微信模板消息驻场人员openid
        CaseMemberDto caseMemberDto = new CaseMemberDto();
        caseMemberDto.setPremisesId(Long.valueOf(premisesId));
        List<PartnerInfo> partnerInfoList = caseMemberService.selectListForWxMsg(caseMemberDto);
        // 筛选出有权限的用户
        partnerInfoList = filterPartnerByPermission(partnerInfoList, agentPi);
        List<String> assignOpenIdList = null;
        if(partnerInfoList != null && partnerInfoList.size() > 0) {
            assignOpenIdList = partnerInfoList.stream().filter(partnerInfo -> partnerInfo.getWxOpenid() != null).map(PartnerInfo::getWxOpenid).collect(Collectors.toList());
        }
        if (CollectionUtils.isEmpty(assignOpenIdList)) {
            logger.error("sendFollowTemplateMsg error ---- 无接收人员,不发送消息！");
            return;
        }
        List<PartnerInfo> reveivePartnerInfos = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(partnerInfoList)) {
            reveivePartnerInfos.addAll(partnerInfoList);
        }
        List<String> hideWxOpenIds = getHideWxOpenIds(assignOpenIdList);
        List<String> hideAgentPhoneOpenIds = getHideAgentPhoneOpenIds(assignOpenIdList);
        //楼盘信息V10BindServiceImpl
        Premises premises = premisesService.selectSimpleById(Long.valueOf(premisesId));
        if(Objects.isNull(premises)) {
            logger.error("sendFollowTemplateMsg error ---- 未获取到楼盘,不发送消息: {}", premisesId);
            return;
        }
        Company company = companyService.selectById(premises.getCompanyId());
        if(Objects.isNull(company)) {
            logger.error("sendFollowTemplateMsg error ---- 未获取到代理公司,不发送消息: {}", premises.getCompanyId());
            return;
        }
        companyUuid = company.getCompanyUuid();

        //经纪人公司名称
        Organization organization = companyService.getOrganizationInfo(agentPi.getHigherid(), agentPi.getDeptId());
        //获取微信模板配置失败
        Map<Integer,WxmsgModel> assistantWxMap = subscriptionApiService.getSubscriptionModelMsg(companyUuid
                , null, SystemIdEnum.ASSISTANT.getCode());
        if (assistantWxMap == null || assistantWxMap.size() == 0 || assistantWxMap.get(WxMessageTemplate.FOLLOW_AUDIT_TEMPLATE_ID) == null) {
            logger.error("sendFollowTemplateMsg error ---- 获取公司模板配置失败: {}", companyUuid);
            return;
        }

        for (String openId : assignOpenIdList) {
            logger.info("sendFollowTemplateMsg ---- openId =========" + openId);
            logger.info("sendFollowTemplateMsg ---- assistantAccessToken =========" + assistantAccessToken);
            try {
                TreeMap<String, HashMap<String, String>> params = new TreeMap<>();
                params.put("first",WechatTemplateMsg.item("跟进信息提醒"));
                String realPhone = getRealPhoneByCaseMemberAuth(hideWxOpenIds, cusPhone, openId, ASSISTANT_SYSTEM, Long.valueOf(premisesId));
                params.put("keyword1",WechatTemplateMsg.item(cusName + " " + realPhone));
                params.put("keyword2",WechatTemplateMsg.item(premises.getName()));
                params.put("keyword3",WechatTemplateMsg.item(currentStatus));
                String agentPhone = getAgentPhoneByCaseMemberAuth(hideAgentPhoneOpenIds, agentPi.getPhone(), openId, ASSISTANT_SYSTEM, Long.valueOf(premisesId));
                params.put("keyword4",WechatTemplateMsg.item(
                        organization.getCompanyName() + " - "
                                + organization.getDepartmentName() + " "
                                //+ organization.getGroupName() + " "
                                //+ organization.getStoreName() + " "
                                + agentPi.getAccountName() + " "
                                + agentPhone));
                StringBuffer sb = new StringBuffer("跟进提交时间: ");
                sb.append(DateUtils.DateToString(DateUtils.getCurrentTS(), DateStyle.YYYY_MM_DD_HH_MM_SS));
                sb.append(", 请及时查看并审核跟进信息。");
                params.put("remark", WechatTemplateMsg.item(sb.toString(), "#000"));

                WechatTemplateMsg wechatTemplateMsg = new WechatTemplateMsg();
                wechatTemplateMsg.setTemplate_id(assistantWxMap.get(WxMessageTemplate.FOLLOW_AUDIT_TEMPLATE_ID).getWxModelmsgId());
                wechatTemplateMsg.setTouser(openId);
                String url = h5UrlConfig.getWxTemplateMsgAssistantUrl() + assistantCusPreDetailUrl.replace(COMPANY_UUID, companyUuid).replace(CUS_PRE_ID, String.valueOf(reportId));
                wechatTemplateMsg.setUrl(url);
                wechatTemplateMsg.setData(params);
                String data = JSON.toJSONString(wechatTemplateMsg);
                TemplateMessageResult result = wechatTemplateMessageService.sendTemplate(assistantAccessToken, data);

                String systemId = SystemIdEnum.ASSISTANT.getCode();
                String receiveOpenId = openId;
                String modelType = String.valueOf(WxMessageTemplate.FOLLOW_AUDIT_TEMPLATE_ID);
                String modelUuid = assistantWxMap.get(WxMessageTemplate.FOLLOW_AUDIT_TEMPLATE_ID).getWxModelmsgId();
                buildWXFailureMsg(getPartnerId(reveivePartnerInfos, receiveOpenId), companyUuid, systemId, receiveOpenId, data, modelType, modelUuid, result, reportId);
                Thread.sleep(1000L);
            } catch (InterruptedException ie) {
                logger.error("sendFollowTemplateMsg InterruptedException---- 发送微信模板消息失败：{}", ie);
            } catch (Exception e) {
                logger.error("sendFollowTemplateMsg error ---- 发送微信模板消息失败：{}", e);
            }
        }
    }

    private void buildWXFailureMsg(Long partnerId, String companyUuid, String systemId, String openId, 
    		String content, String wxmodelType, String wxmodelUuid, TemplateMessageResult result, Long cusPreid){
        WxmsgFailureDto wfDto = new WxmsgFailureDto();
        if(StringUtils.isEmpty(companyUuid)){
            return;
        }
        wfDto.setCompanyUuid(companyUuid);
        wfDto.setSystemId(systemId);
        wfDto.setReceiveOpenid(openId);
        wfDto.setPartnerId(partnerId);
        wfDto.setCusPreid(cusPreid);
        wfDto.setReceiveContent(content);
        wfDto.setWxmodelType(wxmodelType);
        wfDto.setWxmodelUuid(wxmodelUuid);
        wfDto.setIsResend(false);
        if(!"ok".equals(result.getErrmsg().toLowerCase())) {
            //根据之前的SQL 判定是否进行重发机制  result like '%40001%' OR result like '%system error%'
            if (40001 == result.getErrcode() || StringUtils.contains(result.getErrmsg(),"system error")){
                wfDto.setIsResend(true);
                wfDto.setSendStatus(SendStatusEnum.RESEND.getNo());
            }else {
                wfDto.setSendStatus(SendStatusEnum.FAILURE.getNo());
            }
        }else{
            wfDto.setSendStatus(SendStatusEnum.SUCCESS.getNo());
        }
        wfDto.setResult(JSONObject.toJSONString(result));
        wfDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
        wfDto.setCreateTime(Calendar.getInstance().getTime());

        logger.info("进入DAO层之前----新增微信记录 {}", JSONObject.toJSONString(wfDto));
        wxmsgFailureService.create(wfDto);
    }
    
    /**
     *  判断案场人员是否要展示所有的号码还是前三后四
     * @param wxOpenIds
     */
    private List<String> getHideWxOpenIds(List<String> wxOpenIds) {
    	List<String> hideWxOpenIds = new ArrayList<>();
    	if(wxOpenIds == null || wxOpenIds.size() == 0) {
    		return hideWxOpenIds;
    	}
    	//隐藏的集合
    	return partnerInfoService.getPhoneHideByOpenId(wxOpenIds);
    }

    /**
     * 根据案场人员的展示权限获取真正展示的电话号码,不是案场人员，则不发送
     * @param hideWxOpenIds
     * @param phone
     * @param wxOpenId
     * @param systemType
     * @return
     */
    private String getRealPhoneByCaseMemberAuth(List<String> hideWxOpenIds, String phone, String wxOpenId, String systemType, Long premisesId) {
    	// 不是案场人员则不进行转换
    	if(!ASSISTANT_SYSTEM.equals(systemType)) {
    		return phone;
    	}
    	if(StringUtils.isEmpty(wxOpenId)) {
    		logger.info("未传入wxOpenId，直接返回phone");
    		return phone;
    	}
    	if(phone.isEmpty() || phone.length() != 11) {
    		logger.info("phone格式异常，直接返回phone，传入phone为" + phone);
    		return phone;
    	}
    	//如果需要隐藏，则返回替换后的手机号
    	for (String hideWxOpenId : hideWxOpenIds) {
			if(wxOpenId.equals(hideWxOpenId)) {
				String hidePhone = ReportWayEnum.convertMobileByReportWay(phone, ReportWayEnum.BEFORE_THREE_AFTER_FOUR.getNo());
				return hidePhone;
			}
		}
    	return phone;
    }

    /**
     * 获取需要隐藏
     * @param wxOpenIds
     */
    private List<String> getHideAgentPhoneOpenIds(List<String> wxOpenIds) {
        List<String> hideWxOpenIds = new ArrayList<>();
        if(wxOpenIds == null || wxOpenIds.size() == 0) {
            return hideWxOpenIds;
        }
        //隐藏的集合
        return partnerInfoService.getHideAgentPhoneOpenIds(wxOpenIds);
    }

    /**
     * 根据案场人员的展示权限获取真正展示的经纪人电话号码
     * 不是案场人员,不处理
     * @param hideAgentPhoneOpenIds
     * @param agentPhone
     * @param wxOpenId
     * @param systemType
     * @return
     */
    private String getAgentPhoneByCaseMemberAuth(List<String> hideAgentPhoneOpenIds, String agentPhone, String wxOpenId, String systemType, Long premisesId) {
        // 不是案场人员则不进行转换
        if(!ASSISTANT_SYSTEM.equals(systemType)) {
            return agentPhone;
        }
        if(StringUtils.isEmpty(wxOpenId)) {
            return agentPhone;
        }
        if(agentPhone.isEmpty() || agentPhone.length() != 11) {
            return agentPhone;
        }
        //如果需要隐藏，则返回替换后的手机号
        if(hideAgentPhoneOpenIds.contains(wxOpenId)){
            agentPhone = ReportWayEnum.convertMobileByReportWay(agentPhone, ReportWayEnum.BEFORE_THREE_AFTER_FOUR.getNo());
        }
        return agentPhone;
    }


    /**
     * 过滤无报备人数据权限的用户
     * @param partnerInfoList
     * @return
     */
    private List<PartnerInfo> filterPartnerByPermission(List<PartnerInfo> partnerInfoList, PartnerInfo agentPi){
        List<PartnerInfo> validPartners = new ArrayList<>();
        if(CollectionUtils.isEmpty(partnerInfoList)){
            return partnerInfoList;
        }
        for(PartnerInfo partnerInfo: partnerInfoList){
            List<Long> permissionDeptIds = deptPermissionService.getPartnerDeptPermission(partnerInfo.getId());
            if(CollectionUtils.isEmpty(permissionDeptIds)){
                validPartners.add(partnerInfo);
            }else{
                if(permissionDeptIds.contains(agentPi.getDeptId())){
                    validPartners.add(partnerInfo);
                }
            }
        }
        return validPartners;
    }
    
    public static final String[] CHECK_TYPE_ARRAY = new String[] {"partnerCheck", "companyCheck"};
    
    /**
     * 	发送审核消息
     */
    @Async
	@Override
	public void sendCheckTemplateMsg(String companyUuid, 
			PartnerInfo partnerInfo, boolean checkResult, String remark, String type) {
    	String wxOpenid = partnerInfo.getWxOpenid();
    	if(!StringUtil.isNotNull(wxOpenid)) {
    		logger.info("sendPartnerCheckSuccessTemplateMsg->当前人员未关注公众号。id：{}", partnerInfo.getId());
        	return;
    	}
    	String  loginType = partnerInfo.getLastLoginSystemId();
    	// 1、获取company 并进行校验
    	CompanyDto companyDto = new CompanyDto();
    	companyDto.setCompanyUuid(companyUuid);
    	Company company = companyService.selectByDto(companyDto);
    	if(company == null) {
        	logger.info("sendPartnerCheckSuccessTemplateMsg->company is null。companyUuid{}", companyUuid);
        	return;
        }
    	// 2、 获取token
    	String accessToken = wxAccessTokenCacheUtils.getAccessTokenIfWeappMsg(company, loginType, "");
    	if(!StringUtil.isNotNull(accessToken)) {
    		logger.info("sendPartnerCheckSuccessTemplateMsg->accessToken 获取异常", companyUuid);
        	return;
    	}
    	// 3、获取模板
    	String modelSystemId = (SystemIdEnum.WEAPP_AGENCY.getCode().equals(loginType) 
    			&& "1".equals(company.getEnableWeappMsg()))? 
    					SystemIdEnum.WEAPP_AGENCY_WX_ACCOUNTS.getCode(): SystemIdEnum.AGENCY_h5.getCode();
    	Map<Integer,WxmsgModel> agencyWxMap = subscriptionApiService.getSubscriptionModelMsg(companyUuid
                , "", modelSystemId);
    	if(agencyWxMap == null || agencyWxMap.size() == 0) {
        	logger.info("sendPartnerCheckSuccessTemplateMsg->agencyWxMap is null, 请检查运营后台配置:companyUuid{}", companyUuid);
        	return;
        }
    	String templateId = agencyWxMap.get(WxMessageTemplate.PREMISES_SHELVE_TEMPLATE_ID).getWxModelmsgId();
    	
    	// 4、拼装下发内容
    	TreeMap<String, HashMap<String, String>> params = new TreeMap<>();
    	WechatTemplateMsg wechatTemplateMsg = new WechatTemplateMsg();
    	wechatTemplateMsg.setTemplate_id(templateId);
        wechatTemplateMsg.setTouser(partnerInfo.getWxOpenid());
        
        packCheckMsg(type, checkResult, params, wechatTemplateMsg, remark);
        Long companyId = 0L;
        if(CHECK_TYPE_ARRAY[1].equals(type) && checkResult) {
        	companyId = partnerInfo.getHigherid();
        }
        
        wechatTemplateMsg.setData(params);
        addMiniProgram(loginType, company.getCompanyUuid(), company.getEnableWeappMsg(), wechatTemplateMsg, companyId);
        String data = JSON.toJSONString(wechatTemplateMsg);
        
        TemplateMessageResult result = wechatTemplateMessageService.sendTemplate(accessToken, data);

        String systemId = modelSystemId;
        String modelType = String.valueOf(WxMessageTemplate.PREMISES_SHELVE_TEMPLATE_ID);
        String modelUuid = templateId;
        buildWXFailureMsg(partnerInfo.getId(), companyUuid, systemId, wxOpenid, data, modelType, modelUuid, result, 0L);
        
	}

    /**
     * 	拼装审核参数
     * @param type
     * @param checkResult
     * @param params
     * @param wechatTemplateMsg
     * @param remark
     */
    private void packCheckMsg(String type, boolean checkResult, TreeMap<String, HashMap<String, String>> params,
    		WechatTemplateMsg wechatTemplateMsg, String remark) {
    	if(CHECK_TYPE_ARRAY[0].equals(type) && checkResult) {
    		packPartnerCheckSuccMsg(params, wechatTemplateMsg);
    	} else if(CHECK_TYPE_ARRAY[1].equals(type) && checkResult) {
    		packCompanyCheckSuccMsg(params, wechatTemplateMsg);
    	} else if(CHECK_TYPE_ARRAY[0].equals(type) && !checkResult) {
    		packPartnerCheckFailMsg(params, wechatTemplateMsg, remark);
    	} else if(CHECK_TYPE_ARRAY[1].equals(type) && !checkResult) {
    		packCompanyCheckFailMsg(params, wechatTemplateMsg, remark);
    	}
    }
    /**
     * 	组装人员审核失败消息
     * @param params
     */
    private void packCompanyCheckSuccMsg(TreeMap<String, HashMap<String, String>> params, WechatTemplateMsg wechatTemplateMsg) {
    	params.put("first", WechatTemplateMsg.item("合作机构申请审批通过"));
        params.put("keyword1", WechatTemplateMsg.item("合作机构申请"));
        params.put("keyword2", WechatTemplateMsg.item("审批通过"));
        params.put("remark", WechatTemplateMsg.item("合作机构和管理员账号已开通，小程序可以正常使用，电脑端网址请查收。点击消息进入欢迎页"));
        wechatTemplateMsg.setUrl(MINIPROGRAM_PATH_ARRAY[2]);
    }
    
    /**
     * 	组装人员审核失败消息
     * @param params
     */
    private void packCompanyCheckFailMsg(TreeMap<String, HashMap<String, String>> params, WechatTemplateMsg wechatTemplateMsg, String remark) {
    	params.put("first", WechatTemplateMsg.item("合作机构申请审批不通过"));
        params.put("keyword1", WechatTemplateMsg.item("合作机构申请"));
        if(StringUtils.isNotBlank(remark)) {
        	params.put("keyword2", WechatTemplateMsg.item("审核不通过。" + remark));
        }else {
        	params.put("keyword2", WechatTemplateMsg.item("审核不通过。"));
        }
        params.put("remark", WechatTemplateMsg.item("请联系管理员后，重新注册"));
        wechatTemplateMsg.setUrl(MINIPROGRAM_PATH_ARRAY[3]);
    }
    /**
     * 	组装人员审核成功消息
     * @param params
     */
    private void packPartnerCheckSuccMsg(TreeMap<String, HashMap<String, String>> params, WechatTemplateMsg wechatTemplateMsg) {
    	params.put("first", WechatTemplateMsg.item("分销账号注册申请审批通过"));
        params.put("keyword1", WechatTemplateMsg.item("分销账号注册申请"));
        params.put("keyword2", WechatTemplateMsg.item("审批通过"));
        params.put("remark", WechatTemplateMsg.item("分销账号已开通，小程序可以正常使用"));
        wechatTemplateMsg.setUrl(MINIPROGRAM_PATH_ARRAY[0]);
    }
    
    /**
     *	 组装人员审核失败消息
     * @param params
     */
    private void packPartnerCheckFailMsg(TreeMap<String, HashMap<String, String>> params, WechatTemplateMsg wechatTemplateMsg, String remark) {
    	params.put("first", WechatTemplateMsg.item("分销账号注册申请审批不通过"));
        params.put("keyword1", WechatTemplateMsg.item("分销账号注册申请"));
        if(StringUtils.isNotBlank(remark)) {
        	params.put("keyword2", WechatTemplateMsg.item("审批不通过。" + remark));
        }else {
        	params.put("keyword2", WechatTemplateMsg.item("审批不通过。"));
        }
        params.put("remark", WechatTemplateMsg.item("请联系管理员后，重新注册"));
        wechatTemplateMsg.setUrl(MINIPROGRAM_PATH_ARRAY[1]);
    }
}
